36

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?

    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? discusses similar problem of Linq-to-Entites not able to translate .ToString() method, but approaches suggested there - not using method at all or getting Microsoft to fix it did not work for this case.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
jfk
  • 361
  • 1
  • 3
  • 4

1 Answers1

64

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

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(); 
jmoerdyk
  • 5,544
  • 7
  • 38
  • 49