c# - 需要帮助使用嵌套关联和 SUM 优化 Linq-to-SQL
问题描述
我有一个想要提高性能的 LINQ。我目前正在运行的查询是
item.ShipmentLines.Where(p => p.Shipment.TxnDate < dt).Sum(p => p.Quantity);
whereShipmentLines
与一个 item 对象相关联,并通过 .NET 实体框架ShipmentLines
与所有相关联。Shipments
运行此程序并查看生成的 SQL 时,我发现它正在查询以检查每个关联装运的 Shipment.TxnDate where 子句,然后将所有匹配的装运线记录返回到服务器,然后运行 SUM . 我想做的是更像
SELECT SUM(Quantity)
FROM ShipmentLine sl
LEFT OUTER JOIN shipment s ON s.ShipmentId = sl.ShipmentId
WHERE sl.itemid = @itemid
AND s.TxnDate > @dt
itemid
以上是调用上述 LINQ 代码的对象的 id。
我无法强制 LINQ 将此查询优化为一个在 SQL 中直接执行相当简单的语句。
有谁知道如何优化它以生成上面的单个语句?
编辑:为上面的 LINQ 生成的代码这是生成的 SQL。
SELECT [t0].[ShipmentLineId], [t0].[ShipmentId], [t0].[Quantity], [t0].[ItemId], ..all the other columns..
FROM [dbo].[ShipmentLine] AS [t0]
WHERE [t0].[ItemId] = @p0
然后是所有相关货物的几千次
SELECT [t0].[ShipmentId], [t0].[TxnDate], ..all the other columns..
FROM [dbo].[Shipment] AS [t0]
WHERE [t0].[ShipmentId] = @p0
解决方案
推荐阅读
- javascript - Javascript - 如何将字符串'0'转换为数字0
- oracle - 使用 Oracle 更改具有较高日期的所有重复项的字段值
- javascript - Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 only on get request page
- php - 在 JOIN 中获取完全相同的列时出现问题
- sql - Oracle SQL如何消除特定列的重复行
- javascript - 使用 Vue CLI 在 Node js 上进行 Express Session
- c++ - * 类型的参数与 * 类型的参数不兼容
- node.js - Discord.JS - 如何有条件地在嵌入中设置字段?
- batch-file - 如何使用 CMD 在变量中写入可移动设备的字母?
- php - PHPMailer 挂起邮件发送