C# 如何使用 LINQ 从实体加载最后一条记录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19121663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to load just the last record from entity with LINQ?
提问by amin
I want to fetch value of field named "Gram" from the last record and put its value into a variable, without using any conditions.
我想从最后一条记录中获取名为“Gram”的字段的值并将其值放入一个变量中,而不使用任何条件。
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.
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.
采纳答案by Habib
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:
Last
或LastOrDefault
在 LINQ to Entities 中不受支持。您可以使用ToList
or迭代您的查询ToArray
,然后应用,Last
或者您可以按降序排序,然后使用First
类似的方法:
int value = int.Parse(Entity.TblGold
.OrderByDescending(p => p.Gram)
.Select(r => r.Gram)
.First().ToString());
回答by Garrison Neely
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();
回答by Bern
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());
回答by user4060204
You can use order by 1 == 1 and it works
您可以使用 order by 1 == 1 并且它有效
var countOfRows = tbl.Count();
var lastRow = tbl.OrderBy(c => 1 == 1).Skip(countOfRows - 1).FirstOrDefault();