[英]LINQ to Entities group-by failure using .date
我想在日期時間字段的日期部分做一個Linq組。
這個linq語句可以工作,但它按日期和時間分組。
var myQuery = from p in dbContext.Trends
group p by p.UpdateDateTime into g
select new { k = g.Key, ud = g.Max(p => p.Amount) };
當我運行此語句僅按日期分組時,我得到以下錯誤
var myQuery = from p in dbContext.Trends
group p by p.UpdateDateTime.Date into g //Added .Date on this line
select new { k = g.Key, ud = g.Max(p => p.Amount) };
LINQ to Entities不支持指定的類型成員“Date”。 僅支持初始值設定項,實體成員和實體導航屬性。
我如何按日期而不是日期和時間進行分組?
使用EntityFunctions.TruncateTime方法:
var myQuery = from p in dbContext.Trends
group p by EntityFunctions.TruncateTime(p.UpdateDateTime) into g
select new { k = g.Key, ud = g.Max(p => p.Amount) };
這里可能的解決方案遵循以下模式:
var q = from i in ABD.Listitem
let dt = p.EffectiveDate
group i by new { y = dt.Year, m = dt.Month, d = dt.Day} into g
select g;
因此,對於您的查詢[未經測試]:
var myQuery = from p in dbContext.Trends
let updateDate = p.UpdateDateTime
group p by new { y = updateDate.Year, m = updateDate.Month, d = updateDate.Day} into g
select new { k = g.Key, ud = g.Max(p => p.Amount) };
您不能在Linq-to-Entities查詢中使用DateTime.Date
。 您可以顯式擁有字段組,也可以在數據庫中創建Date
字段。 (我有同樣的問題 - 我在數據庫中使用了一個Date
字段,從未回頭看過)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.