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

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


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());


You can't do it in one query, but you can do it in two.

var countOfRows = tbl.Count();var lastRow = tbl.Skip(countOfRows - 1).FirstOrDefault();


If the list is correctly ordered to grab the last item I'd simply reverse the list then grab the first (previously last) item:

var gram = int.Parse(Entity.TblGold.Reverse().First().Gram.ToString());