[英]Updating database using entity framework throws Null Reference Exception
[英]Using GroupBy DateTime with Entity Framework throws an exception
我正在使用实体框架核心版本 3.1.5。
我想按日期对结果进行分组,比如说按年。 我的最终目标是获得一个组实体的某些属性的总和,但我什至无法在没有总和的情况下进行分组。 我尝试了以下链接中的所有答案,但所有尝试都以抛出异常结束,并显示消息
“System.InvalidOperationException:无法翻译 LINQ 表达式 'DbSet.GroupBy(XXX)},keySelector: YYY)'。要么以可翻译的形式重写查询,要么通过插入调用显式切换到客户端评估AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync()”。
代码示例:
var result = await _tenantDbContext.MetricEntities.GroupBy(o => new { o.MetricType, o.CreatedDate.Value.Year }).Select(g => g.Sum(o => o.Value)).ToListAsync();
var result = await _metricRepository.GetQueryable().GroupBy(metric => DbFunctions.TruncateTime(metric.CreatedDate)).OrderBy(group => group.Key).ToListAsync();
var result = await _metricRepository.GetQueryable().GroupBy(metric => DbFunctions.CreateTime(metric.CreatedDate.Value.Year,null,null)).ToListAsync()
var result = _tenantDbContext.MetricEntities
.GroupBy(x =>
SqlFunctions.DateAdd("month", SqlFunctions.DateDiff("month", sqlMinDate, x.CreatedDate),
sqlMinDate))
.Select(x => new
{
Period = x.Key // DateTime type
}).ToListAsync();
var result = await _globalDbContext.MetricEntities.GroupBy(x =>
new
{
Year = x.CreatedDate.Value.Year
},
s => new
{
InsertCount = s,
}
).Select(g=>new
{
InsertCount = g.Count(),
}).ToListAsync();
链接:
https://atashbahar.com/post/2017-04-27-group-by-day-week-month-quarter-and-year-in-entity-framework
https://entityframework.net/knowledge-base/19225895/linq---grouping-by-date-and-selecting-count
更多链接:
https://www.codeproject.com/Questions/1199021/LINQ-group-by-month-year-and-return-a-sum
https://www.mikesdotnetting.com/article/257/entity-framework-recipe-grouping-by-year-and-month
https://www.mikesdotnetting.com/article/257/entity-framework-recipe-grouping-by-year-and-month
仔细看看错误,它是关于: linq
, GroupBy
和它的选择器,它告诉它不能“翻译”。
您正在尝试执行 SQL 中不支持的操作,很可能在 lambda 中调用 C# function。 所以,基本上它是在说:要么改变它,要么在 memory 中做。
最快的修复方法是在 memory 中进行,但会导致大量数据传输。
所以而不是:
var restult = db.Table.Where(...).GroupBy(...).ToList();
尝试:
var restult = db.Table.ToList().Where(...).GroupBy(...);
//or
var restult = db.Table.Where(...).ToList().GroupBy(...);
唯一适合我的是:
_dbContext.metricEntities.GroupBy(metricEntity =>new
{
Year = Microsoft.EntityFrameworkCore.EF.Property<DateTime>(metricEntity, "CreatedDate").Date.Year,
}
).Select(entities =>
new MetricGraphNode
{
X = new DateTime(entities.Key.Year, 1, 1).ToString("yyyy"),
Y = entities.Sum(k => k.Value),
}).ToList();
当然,您可以添加月、日、小时等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.