【问题标题】:LINQ to Entities does not recognize the method 'System.DateTime GetValueOrDefault()'LINQ to Entities 无法识别方法“System.DateTime GetValueOrDefault()”
【发布时间】:2014-10-31 22:33:09
【问题描述】:

在其他类中运行类似代码的情况下,使用非常简单的代码无法正常工作。如果我删除 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;
    }

Why would Entity Framework not be able to use ToString() in a LINQ statement? 讨论了 Linq-to-Entites 无法翻译 .ToString() 方法的类似问题,但那里建议的方法 - 根本不使用方法或让 Microsoft 修复它不适用于这种情况。

【问题讨论】:

    标签: c# .net linq linq-to-entities


    【解决方案1】:

    您应该可以使用Null Coalescing 运算符??

    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(); 
    

    【讨论】:

    • 太棒了,这为我节省了很多时间!
    猜你喜欢
    • 1970-01-01
    • 2015-10-12
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多