你的位置:首页 > ASP.net教程

[ASP.net教程]“entities.LastOrDefault()”引发了类型“System.NotSupportedException”的异常


问题:

var entities = new ShipuPlanBLO().UserList(userId, beginDate, endDate);DateTime maxDate = entities.FirstOrDefault().PlanDate;DateTime minDate = entities.LastOrDefault().PlanDate; //报错

说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 
异常详细信息: System.NotSupportedException: LINQ to Entities 不识别方法“AdminDB.Models.PlanList LastOrDefault[PlanList](System.Linq.IQueryable`1[AdminDB.Models.PlanList])”,因此该方法无法转换为存储表达式。

 

----------------------------------------------------------------------------------------------------------------------------------------

解决方法:

That's because LINQ to Entities (and databases in general) does not support all the LINQ methods (see here for details: http://msdn.microsoft.com/en-us/library/bb738550.aspx)

What you need here is to order your data in such a way that the "last" record becomes "first" and then you can use FirstOrDefault. Note that databasese usually don't have such concepts as "first" and "last", it's not like the most recently inserted record will be "last" in the table.

问题链接:https://social.msdn.microsoft.com/Forums/vstudio/en-US/2ccc7935-c6f5-4bf2-a4cd-0a6de9e38ed8/firstordefault-and-lastordefault?forum=wpf

 

简单来说就是 LINQ to Entities 不支持所有的LINQ方法,LastOrDefault也是不支持的方法之一

[That's because LINQ to Entities (and databases in general) does not support all the LINQ methods ]