Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 738
Sachin Kainth Avatar asked Feb 27 '26 23:02

Sachin Kainth


2 Answers

You can't call C# methods in EF queries, because EF doesn't know how to turn the method into SQL.

Instead, call .AsEnumerable() first to force the Where() to run locally.

like image 182
SLaks Avatar answered Mar 02 '26 07:03

SLaks


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);
like image 30
Sorax Avatar answered Mar 02 '26 08:03

Sorax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!