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.
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.
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With