首页 > 解决方案 > 需要帮助使用嵌套关联和 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

标签: c#.netlinqlinq-to-sql

解决方案


推荐阅读