![](/img/trans.png)
[英]How can I access all values from a specific column in tables using linq and Entity Framework?
[英]How can I retrieve the biggest date and time from the column using Linq to entity?
我在SQL表中有一個名為DateMeasure
datetime列。
我在.net項目中使用實體框架6。
這是我的桌子的例子:
Id | NumberP | TrackNumber | DateMeasure
28092|15240000|1.0.7.1782|2009040004731|2008-01-20 13:10:22.000
28094|61615000|1.0.7.1782|2009040007696|2010-05-20 13:11:38.000
28095|95317000|1.0.7.1782|2009040007695|2011-08-20 13:10:18.000
28101|15240000|1.0.7.1782|2009040004740|2015-11-20 14:10:22.000
28103|61615000|1.0.7.1782|2009040007690|2015-11-20 14:11:38.000
28104|95317000|1.0.7.1782|2009040007710|2009-02-20 14:10:18.000
我想借助Linq從表中獲取到實體的行:
28103|61615000|1.0.7.1782|2009040007690|2015-11-20 14:11:38.000
如何使用Linq到實體從列中檢索最大(最新) 日期和時間 ?
您可以使用Max
擴展名獲取最長日期:
var maxDate = context.Table.Max(m => m.DateMeasure);
然后,您可以使用FirstOrDefault
來獲取該實體:
var model = context.Table.FirstOrDefault(m => m.DateMeasure == maxDate);
實際上,您只需要執行一個查詢即可:
var model = context.Table.FirstOrDefault(m => m.DateMeasure == context.Table.Max(x => x.DateMeasure));
您可以在Linq中使用IQuery對象的OrderBy
方法對DateMeasure
列進行排序並獲取第一個條目。
(from s in context.Table
orderby s.DateMeasure descending).First()
或搭配:
context.Table
.OrderByDescending(s => s.DateMeasure)
.First();
OrderByDescending
方法將按降序對查詢進行排序,您也可以使用OrderBy
按升序進行排序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.