使用LINQ选择最后一条记录失败并显示“方法未被识别”。

3
我有以下查询语句来选择数据库中的最后一条记录。
using (Entities ent = new Entities())
{
Loaction last = (from x in ent.Locations select x).Last();
Location add = new Location();
add.id = last.id+1;
//some more stuff
}

通过"直接事件"在Ext.NET中调用包含这些行的方法时,将返回以下错误:

LINQ to Entities does not recognize the method 'Prototype.DataAccess.Location Last[Location]
(System.Linq.IQueryable`1[Prototype.DataAccess.Location])' method,
and this method cannot be translated into a store expression.

table structure is following:

int ident IDENTITY NOT NULL,
int id NOT NULL,
varchar(50) name NULL,
//some other varchar fields

1
请查看这个问题:https://dev59.com/sGw05IYBdhLWcg3wVwg4 - default locale
1个回答

13

Linq to Entities 不支持 Last。请使用 OrderByDescending(通常是按照 ID 或某个日期列)并选择第一个。类似于:

Location last = (from l in ent.Locations
                 orderby l.ID descending
                 select l).First();

或者

Location last = ent.Locations.OrderByDescending(l => l.ID).First();

请参考 MSDN 文章 支持和不支持的 LINQ 方法(LINQ to Entities)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接