我正在开始构建KPI(关键绩效指标(仪表板,我正在努力寻找最优化的方法。欢迎提出建议。
我试着只使用LINQ(在EF Core 3.1中(。
在我的模型中,1个ProductionRecord可以有N个ProductionCellRecords。我正试图做这样的事情(将去年的所有记录分组,并对好的组件进行汇总,等等(:
var data = _context.ProductionRecords
.Where(pr => pr.StartedAt < DateTime.Now &&
pr.StartedAt.AddDays(365) >= DateTime.Now)
.AsEnumerable()
.GroupBy(pr => pr.StartedAt.Month)
.Select(g => new { name = g.Key,
goodComponents = g.Select(pr => pr.ProductionCellRecords.Sum(pcr => pcr.GoodComponents)),
badComponents = g.Select(pr => pr.ProductionCellRecords.Sum(pcr => pcr.BadComponents)) });
但是g.Select(pr => pr.ProductionCellRecords.Sum(pcr => pcr.GoodComponents))
并没有返回Sum,而是返回{System.Linq.Enumerable.SelectIListIterator<NoPaper.Models.ProductionRecord, int>}
。无论如何,我发现GroupBy
的工作方式与SQLGroupBy
不同,除非它有一个聚合函数
Q:所以我想知道我在上面的查询中做错了什么,以及查询数据库以满足我的需求的最佳/最优化的方法是什么。
我的型号/类别
public class ProductionRecord
{
public int Id { get; set; }
public DateTime StartedAt { get; set; }
...
public ICollection<ProductionCellRecord> ProductionCellRecords { get; set; }
}
public class ProductionCellRecord
{
public int Id { get; set; }
public int ProductionRecordId { get; set; }
...
public ProductionRecord ProductionRecord { get; set; }
}
您编写的查询无法翻译。GroupBy有严重的限制,不能与LINQ to Objects一起使用。
var query =
from pr in _context.ProductionRecords
from pcr in pr.ProductionCellRecords
where pr.StartedAt < DateTime.Now && pr.StartedAt.AddDays(365) >= DateTime.Now
group pcr by pr.StartedAt.Month into g
select new
{
name = g.Key,
goodComponents = g.Sum(x => x.GoodComponents),
badComponents = g.Sum(x => x.BadComponents)
}