Muthu
Muthu

Reputation: 1550

ASP.NET MVC LINQ query

When I use the query

var NewMatchs = (from x in entity.matches select x).LastOrDefault();

I get error like this

LINQ to Entities does not recognize the method 'SocialSports.Models.match LastOrDefaultmatch' method, and this method cannot be translated into a store expression.

What's wrong in my code ???

Thanks...

Upvotes: 5

Views: 1788

Answers (3)

Mahesh Velaga
Mahesh Velaga

Reputation: 21971

LastOrDefault is not supported in Linq to Entities. You can achieve the same using the following:

var lastmatch = (from x in entity.matches select x)
                      // Assuming you have some kind of timestamp
                     .OrderByDescending(s => s.Date) 
                     .FirstOrDefault();

Upvotes: 8

Jakub Konecki
Jakub Konecki

Reputation: 46008

You can't use LastOrDefault to query EF entities, as it cannot be translated to T-SQL.

Not all the LINQ methods are supported by Linq to Entities.

List of ALL supported / not supported methods:

http://msdn.microsoft.com/en-us/library/bb738550.aspx

You could try

var NewMatchs = (from x in entity.matches select x).ToList().LastOrDefault();

but this will load ALL matches from the db and perform Linq to objects.

Or try sorting and call FirstOrDefault.

Upvotes: 7

Related Questions