Vogel612
Vogel612

Reputation: 5647

Selecting last record by linq fails with "method not recognised"

i have following query to select the last record in the database

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
}

the following error is returned when calling the method containing these lines via "Direct event" on 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

Upvotes: 3

Views: 7642

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

Last is not supported by Linq to Entities. Do OrderByDescending (usually by ID or some date column) and select first. Something like:

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

Or

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

See MSDN article Supported and Unsupported LINQ Methods (LINQ to Entities) for reference.

Upvotes: 13

Related Questions