Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load just the last record from entity with LINQ?

I want to fetch value of field named "Gram" from the last record and put its value into a variable, without using any conditions.

First I tried

int value = int.Parse(Entity.TblGold.LastOrDefault().Gram.ToString());

Second I tried

int value = int.Parse(Entity.TblGold.Select(p => p.Gram).Last().ToString());

I just receive this exception:

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

like image 808
amin Avatar asked Oct 01 '13 16:10

amin


People also ask

How do I get the last record in Entity Framework?

Answer: If you want to get the most recent record from the database using EF Core or Entity Framework then you must order the result then get FirstOrDefault() record from the dataset returned.

Is LINQ to SQL obsolete?

LINQ to SQL was the first object-relational mapping technology released by Microsoft. It works well in basic scenarios and continues to be supported in Visual Studio, but it's no longer under active development.

How do you use take and skip in LINQ?

The Take operator is used to return a given number of elements from an array and the Skip operator skips over a specified number of elements from an array. Skip, skips elements up to a specified position starting from the first element in a sequence.

Can I use LINQ with dapper?

LINQPad is great for testing database queries and includes NuGet integration. To use Dapper in LINQPad press F4 to open the Query Properties and then select Add NuGet. Search for dapper dot net and select Add To Query.


1 Answers

Last or LastOrDefault are not supported in LINQ to Entities. You can either iterate your query using ToList or ToArray and then apply Last or you can order by descending and then use the First like:

int value = int.Parse(Entity.TblGold
                            .OrderByDescending(p => p.Gram)
                            .Select(r => r.Gram)
                            .First().ToString());
like image 116
Habib Avatar answered Oct 11 '22 15:10

Habib