LINQ to Entities无法识别方法'System.DateTime GetValueOrDefault()'[duplicate]

时间:2021-07-16 16:09:47

This question already has an answer here:

这个问题在这里已有答案:

Struggling with very simple code that isn't working where similar code is working in other classes. It won't compile if I remove GetValueOrDefault(). Also I am using System.Linq. I'm getting this runtime error: LINQ to Entities does not recognize the method 'System.DateTime GetValueOrDefault()'. Any ideas?

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

1 个解决方案

#1


38  

You should be able to use the Null Coalescing operator ??:

你应该能够使用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(); 

#1


38  

You should be able to use the Null Coalescing operator ??:

你应该能够使用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();