簡體   English   中英

嘗試使用Linq2Sql從表中獲取最大日期

[英]Trying to get max date from table using Linq2Sql

以下linq2sql代碼使我非常頭疼,我希望有人可以幫助您

 DateTime _maxRecordedDate = (from snapshot in _ctx.Usage_Snapshots
                                         where snapshot.server_id == server_id
                                         orderby snapshot.reported_on descending
                                         select snapshot.reported_on).First().Value;

該代碼可在LinqPad中運行,並且可以正常編譯,但是在項目運行時會出現“不支持指定方法”的信息。

如果我不使用Value或進行強制轉換,則會出現以下錯誤:

**

無法隱式轉換類型'System.DateTime?' 到“ System.DateTime”。 存在顯式轉換(您是否缺少演員表?)

**

是否不需要First()。Value? 也許只是First()。

我在看這個

DateTime? _maxRecordedDate = _ctx.Usage_Snapshots.Where(s => s.server_id == server_id).Max(d => d.reported_on);

Robert提供了一種更好的方法,但是代碼的問題是您正在調用.Value,並且它將在SQL Server的上下文中運行,因此沒有可轉換為SQL的.Value操作。 您必須調用.ToList()。First()。Value,或分配給DateTime?。 由於您無法調用.First()。ToList()...因為First()返回單個DateTime? 那么最好只分配給DateTime ?,因為您不想從SQL返回整個列表。

經過大量搜索,我發現問題出在使用ADO.NET數據服務。 顯然,他們使用了有限的Linq子集,並且當前無法使用Max,First等方法。Bummme

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM