質問

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