【问题标题】:Selecting last record by linq fails with "method not recognised"通过 linq 选择最后一条记录失败,“方法无法识别”
【发布时间】:2013-02-19 14:21:40
【问题描述】:

我有以下查询来选择数据库中的最后一条记录

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.

表结构如下:

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

【问题讨论】:

标签: linq linq-to-entities


【解决方案1】:

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 文章 Supported and Unsupported LINQ Methods (LINQ to Entities) 以供参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多