LINQ to Entities不识别方法';System.DateTime GetValueOrDefault(

本文关键字:System DateTime GetValueOrDefault Entities to 识别 方法 LINQ | 更新日期: 2023-09-27 18:28:35

在其他类中使用类似代码的情况下,与不起作用的非常简单的代码作斗争。如果我删除GetValueOrDefault(),它将不会编译。此外,我正在使用System.Linq。我收到以下运行时错误:LINQ to Entities无法识别方法"System.DateTime GetValueOrDefault()"。有什么想法吗?

    public List<AddressModel> GetAll(string customer_number)
    {           
        addresses = (from a in db.ADDRESS
                      where a.CUSTOMER_NUMBER.Equals(customer_number)
                      select new AddressModel
                       {
                           Address_Id = a.ADDRESS_ID,
                           System_Id = a.SYSTEM_ID,
                           Customer_Number = a.CUSTOMER_NUMBER,
                           Address_Type = a.ADDRESS_TYPE,
                           Changed_On = a.CHANGED_ON.GetValueOrDefault(DateTime.MinValue),
                           Created_On = a.CREATED_ON.GetValueOrDefault(DateTime.MinValue),
                           Email = a.EMAIL
                       }).ToList(); 
        return addresses;
    }

为什么实体框架不能在LINQ语句中使用ToString()?讨论了Linq和Entites无法翻译.ToString()方法的类似问题,但那里建议的方法——根本不使用方法或让Microsoft修复它——在这种情况下不起作用。

LINQ to Entities不识别方法';System.DateTime GetValueOrDefault(

您应该能够使用Null合并运算符??:

addresses = (from a in db.ADDRESS
             where a.CUSTOMER_NUMBER.Equals(customer_number)
             select new AddressModel
             {
                 Address_Id = a.ADDRESS_ID,
                 System_Id = a.SYSTEM_ID,
                 Customer_Number = a.CUSTOMER_NUMBER,
                 Address_Type = a.ADDRESS_TYPE,
                 Changed_On = a.CHANGED_ON ?? DateTime.MinValue,
                 Created_On = a.CREATED_ON ?? DateTime.MinValue,
                 Email = a.EMAIL
              }).ToList();