Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 685
Muthu Avatar asked Feb 01 '11 10:02

Muthu


People also ask

What is LINQ query in MVC?

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.

What is LINQ query in asp net?

LINQ applies the principles of object-oriented programming to relational data. It provides a unified programming model for querying data from different types of data sources, and extends data capabilities directly into the C# and Visual Basic languages. For more information, see Language-Integrated Query (LINQ).

Is LINQ faster than SQL?

We can see right away that LINQ is a lot slower than raw SQL, but compiled LINQ is a bit faster. Note that results are in microseconds; real-world queries may take tens or even hundreds of milliseconds, so LINQ overhead will be hardly noticeable.

What are LINQ queries in C#?

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.


3 Answers

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();
like image 155
Mahesh Velaga Avatar answered Oct 20 '22 22:10

Mahesh Velaga


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.

like image 40
Jakub Konecki Avatar answered Oct 20 '22 22:10

Jakub Konecki


See The query operator 'LastOrDefault' is not supported

like image 1
Gideon Avatar answered Oct 20 '22 22:10

Gideon