You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:36:08