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

如何在Entity Framework中实现SQL语句的SUM列求和操作

问题

我的数据表结构如下:
数据表结构

请问如下SQL语句要如何在Entity Framework中实现:
待转换SQL语句

非常感谢大家提供的任何帮助与解答。


解答

你可以直接用LINQ语句实现和该SQL完全等价的查询,以下是具体实现方式,优先推荐带导航属性的写法,代码最简洁:

前提

确保你的项目实体配置符合要求:

  • OrderDetail 实体包含导航属性 Order(关联对应订单)、Product(关联对应产品)
  • 自定义DbContext中已添加对应实体的DbSet属性

最简实现(已配置导航属性场景)

// 替换为你项目中实际的DbContext初始化逻辑
using var context = new YourBusinessDbContext();
// 替换为实际业务需要查询的目标客户ID
var targetCustomerId = "待查询的客户ID值";

var result = context.OrderDetails
    .Where(od => od.Order.CustomerId == targetCustomerId)
    .GroupBy(od => new { od.Product.ProductId, od.Product.ProductName })
    .Select(g => new 
    {
        g.Key.ProductId,
        g.Key.ProductName,
        TotalPurchasedQuantity = g.Sum(od => od.Quantity),
        TotalSpentAmount = g.Sum(od => od.Quantity * od.UnitPrice)
    })
    .ToList();

无导航属性实现(手动关联)

如果你没有配置实体间的导航属性,可以手动写JOIN逻辑,和原生SQL的关联逻辑完全对应:

using var context = new YourBusinessDbContext();
var targetCustomerId = "待查询的客户ID值";

var result = (
    from od in context.OrderDetails
    join o in context.Orders on od.OrderId equals o.OrderId
    join p in context.Products on od.ProductId equals p.ProductId
    where o.CustomerId == targetCustomerId
    group od by new { p.ProductId, p.ProductName } into productGroup
    select new 
    {
        productGroup.Key.ProductId,
        productGroup.Key.ProductName,
        TotalPurchasedQuantity = productGroup.Sum(item => item.Quantity),
        TotalSpentAmount = productGroup.Sum(item => item.Quantity * item.UnitPrice)
    }
).ToList();

补充说明

  • 上述写法会被EF翻译为和你提供的原生SQL结构几乎一致的数据库查询,Sum聚合操作会在数据库端执行,不会拉取全量数据到内存计算,性能和手写原生SQL无差异。
  • 如果需要强类型返回值,把Select里的匿名类型替换为你预先定义好的DTO类即可。
  • EF Core和EF6都兼容上述写法,部分低版本EF如果遇到翻译问题,升级小版本即可正常运行。

内容的提问来源于stack exchange,提问作者Rodrigo Gallardo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:24:09