我有以下 linq 到实体查询
from p in Products
where p.ProductId==1219
select new
{
Name = p.ProductName,
count = (from dc in DiscountCodes
where dc.ProductId == p.ProductId
select dc).Count()
}
现在生成的 sql 是(使用 linqpad)
-- Region Parameters
DECLARE @p0 Int = 1219
-- EndRegion
SELECT [t0].[ProductName] AS [Name], (
SELECT COUNT(*)
FROM [DiscountCode] AS [t1]
WHERE [t1].[ProductId] = [t0].[ProductId]
) AS [count]
FROM [Product] AS [t0]
WHERE [t0].[ProductId] = @p0
这似乎不是很有效,特别是如果我需要开始在相关表上添加更多计数。
有没有更好的方法来优化这个查询?
谢谢