如何使用Entity Framework按不含时间的日期分组并按条件求和总金额
实现步骤
首先确保你已经定义好了和表结构匹配的Receipt实体,且在DbContext中注册了对应的DbSet:
// 实体类定义 public class Receipt { public int Id { get; set; } public int? Idcustom { get; set; } public int? Idstaff { get; set; } public DateTime Payat { get; set; } public int Total { get; set; } // 你原表SQL里的totalINT应为笔误,此处修正为total INT对应的属性 } // DbContext中注册 public class YourDbContext : DbContext { public DbSet<Receipt> Receipts { get; set; } // 其他配置省略 }
EF查询写法
你要的查询逻辑有两种写法可选:
- 如果你只需要获取2021-11-13当天的总金额,可以直接聚合查询,代码最简洁:
var targetDate = new DateTime(2021, 11, 13); // 最终返回的totalAmount就是当天的总营收 var totalAmount = yourDbContext.Receipts .Where(r => r.Payat.Date == targetDate) .Sum(r => r.Total);
- 如果你需要严格匹配你给出的原生SQL的分组返回结构,获取日期+总金额的结果集:
var targetDate = new DateTime(2021, 11, 13); var result = yourDbContext.Receipts .Where(r => r.Payat.Date == targetDate) .GroupBy(r => r.Payat.Date) .Select(g => new { PayDate = g.Key, TotalSum = g.Sum(r => r.Total) }) .ToList();
说明
EF(包括EF Core和EF6)会自动将DateTime.Date属性的调用翻译为CAST(payat AS date)的SQL操作,最终生成的SQL和你给出的原生SQL逻辑完全一致,不需要手动拼接转换语句。
内容的提问来源于stack exchange,提问作者Levents
相关产品推荐
相关产品推荐

