문제

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.

도움이 되었습니까?

해결책

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 you have an incremental id:

int idx = tb.Max(i => i.Id);
var row = tb.FirstOrDefault(i => i.Id == idx);

You can use order by 1 == 1 and it works

var countOfRows = tbl.Count();    
var lastRow = tbl.OrderBy(c => 1 == 1).Skip(countOfRows - 1).FirstOrDefault();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top