Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Entities SqlFunctions.DateDiff not supported

I have the following code

DateTime now = DateTime.UtcNow;

var allItemsOver64 = _inventoryContext.Items.Where(i => 
   (SqlFunctions.DateDiff("dd", i.PrimaryInsured.DoB, now) / 365.0) >= 65);

IQueryable<Item> items65To69 = allItemsOver64.Where(i =>
   (SqlFunctions.DateDiff("dd", i.PrimaryInsured.DoB, now) / 365.0) >= 65 &&
   (SqlFunctions.DateDiff("dd", i.PrimaryInsured.DoB, now) / 365.0) <= 69);

But when I try and use allItemsOver64 thus Items65To69.Count() I get this error

The expression ((((Convert(DateDiff("dd", [10007].PrimaryInsured.DoB, 26/04/2012 15:03:09)) / 365) >= 65) And ((Convert(DateDiff("dd", [10007].PrimaryInsured.DoB, 26/04/2012 15:03:09)) / 365) >= 65)) And ((Convert(DateDiff("dd", [10007].PrimaryInsured.DoB, 26/04/2012 15:03:09)) / 365) <= 69)) is not supported.

What am I doing wrong?

like image 447
Sachin Kainth Avatar asked Apr 26 '12 15:04

Sachin Kainth


2 Answers

Maybe you could try using EntityFunctions rather than SqlFunctions.

like image 107
Justin Niessner Avatar answered Nov 15 '22 04:11

Justin Niessner


I understand the original question related to EF 4.1 but just to note EntityFunctions is now obsolete in EF6 (https://msdn.microsoft.com/en-us/library/system.data.entity.core.objects.entityfunctions%28v=vs.113%29.aspx), so DbFunctions should be used instead if targeting EF6 (https://msdn.microsoft.com/en-us/library/system.data.entity.dbfunctions%28v=vs.113%29.aspx).

like image 44
Richard Pursehouse Avatar answered Nov 15 '22 04:11

Richard Pursehouse