Linq to Entities SqlFunctions.DateDiff not supported

女生的网名这么多〃 提交于 2020-01-01 05:33:07

问题


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?


回答1:


Maybe you could try using EntityFunctions rather than SqlFunctions.




回答2:


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).




回答3:


DateDiff function with linq to Entity is following bellow

If you want to

Day difference 
EntityFunctions.DiffDays(startDate , endDate);

Hours diff ->
EntityFunctions.DiffHours(startDate , endDate);

Minuutes diff ->
EntityFunctions.DiffMinutes(startDate , endDate);


来源:https://stackoverflow.com/questions/10336316/linq-to-entities-sqlfunctions-datediff-not-supported

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!