【问题标题】:Entity framework select group by and sum实体框架选择分组和求和
【发布时间】:2016-09-10 12:51:36
【问题描述】:
我正在研究 ASP.NET 和 EF codefirst。
我想用 linq 查询找到最畅销的产品
这是我销售的产品模型
public class FactorItem
{
public int Id { set; get; }
public int ProductId { set; get; }
public int Count { set; get; }
}
【问题讨论】:
标签:
asp.net-mvc
entity-framework
ef-code-first
【解决方案1】:
您必须按 ProductId 进行分组,然后对计数求和并取总和最高的组:
var factorItems = DbContext.FactorItems
.GroupBy(f => f.ProductId)
.OrderByDescending(g => g.Sum(f => f.Count))
.FirstOrDefault()
.Key;
【解决方案2】:
您可以使用 linq 来查找结果。
using(ctx = new Context())
{
var maxValue = ctx.FactorItem.Max(e => e.Count);
var result = ctx.FactoItem.Where(e => e.Count == maxValue);
}