【问题标题】:SELECT and SUM in Entity Framework实体框架中的 SELECT 和 SUM
【发布时间】:2019-12-11 10:50:43
【问题描述】:

我想对所有列和日期之间的上下文进行求和,基本上我想将下面的 SQL 查询转换为 EF:

select meterCategory, sum(cost) maxCost
from [dbo].[UsageData]
where date between '2019-06-25' and '2019-06-25' and 
      cost >= 1
group by meterCategory
order by maxCost desc

【问题讨论】:

    标签: sql entity-framework frameworks entity


    【解决方案1】:
    (var startDate, var endDate) = (new DateTime(2019, 6, 25), new DateTime(2019, 6, 25));
    
    var result = 
      await dbContext.UsageDatas
      .Where(ud => ud.Cost >= 1 && ud.Date >= startDate && ud.Date <= endDate)
      .GroupBy(ud => ud.MeterCategory)
      .Select(g => new { MeterCategory = g.Key, MaxCost = g.Sum(c => c.Cost) })
      .OrderByDescending(g => g.MaxCost)
      .ToListAsync();
    

    您也可以使用元组甚至name their properties,而不是匿名类。

    或者由于您是面向 SQL 的,您可能希望使用 C# LINQ 查询语法(这个使用元组):

    var query =
      from ud in dbContext.UsageDatas
      where ud.Cost >= 1 && ud.Date >= startDate && ud.Date <= endDate
      group ud by ud.MeterCategory into g
      select (MeterCategory: g.Key, MaxCost: g.Sum(ud => ud.Cost)) into r
      orderby r.MaxCost descending
      select r;
    
    var result = await query.ToListAsync();
    

    【讨论】:

      猜你喜欢
      • 2012-05-06
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多