Search code examples
c#linqentity-framework-4linq-to-entities

Linq expression not supported


I have the following LINQ to Entities expression:

var allItemsOver64 =
  _inventoryContext.Items.Where(
  i => DateTimeHelper.CalculateAgeInYears(i.PrimaryInsured.DoB, now) >= 65);

The problem is that when I use allItemsOver64 it says that this expression is not supported. I have a feeling that this error is happening because of the call to the CalculateAgeInYears method. Why is this happening and how can I fix it?

Thanks,

Sachin

Edit:

Even after changing the code to use IEnumerables I still get the same error. Here is my code now:

DateTime now = DateTime.UtcNow;
            var allItemsOver64 =
                _inventoryContext.Items.Where(
                    i => DateTimeHelper.CalculateAgeInYears(i.PrimaryInsured.DoB, now) >= 65).AsEnumerable();
            IEnumerable<Item> items65To69 = allItemsOver64.Where(
                i =>
                DateTimeHelper.CalculateAgeInYears(i.PrimaryInsured.DoB, now) >= 65 &&
                DateTimeHelper.CalculateAgeInYears(i.PrimaryInsured.DoB, now) <= 69).AsEnumerable();

Solution

  • If I infer correctly from your functions name, I think this may be what you're looking for:

    using System.Data.Objects.SqlClient;
    
    var allItemsOver64 = _inventoryContext
                         .Items
                         .Where(i => (SqlFunctions
                                      .DateDiff("dd", i.PrimaryInsured.DoB, now) / 365.0) 
                                      >= 65.0);