LINQ确实让我发疯!我已经使用了很多年了,但是仍然发现使用连接将SQL Server查询放在一起需要5分钟,而在LINQ中做同样的事情要花半天。
以下查询应采用一个productVersion
并检索下游productTOC
字段,然后将它们与userProduct表中的一组单独结果组合,该结果显示每个{{1 }}。 productTOC
和userProduct
之间没有直接链接,因为它们之间存在版本控制层,但我设法通过从productTOC
up 到productTOC
,然后从下到product
,如果有记录,则检索该记录。但是,当我运行查询时,每个userProducts
productTOC
例如:
发生的第一个查询是我所期望的:
private static IEnumerable<CompositeTocDataItem> GetCompositeTocData(P42Entities ctx, int userID, RSPlatform.Data.Core.ProductVersion productVersion)
{
return from toc in productVersion.ProductTOCs
orderby toc.Position
let up = toc.ReferenceProduct?.UserProducts.Where(UP=>UP.UserID == userID).FirstOrDefault()
select new CompositeTocDataItem()
{
Position = toc.Position,
Level = toc.Level,
Name = toc.Name,
ReferenceProductID = toc.ReferenceProductID,
RefCode = toc.RefCode,
ConditionInfo = toc.ConditionInfo,
LastCompletedDate = up?.LastCompletedDate,
Score = up?.Score,
ScoreStatus = up?.ScoreStatus ?? "N",
};
}
,但是对于每个 exec sp_executesql N'SELECT
[Extent1].[ProductVersionID] AS [ProductVersionID],
[Extent1].[Position] AS [Position],
[Extent1].[Level] AS [Level],
[Extent1].[Name] AS [Name],
[Extent1].[RefCode] AS [RefCode],
[Extent1].[ReferenceProductID] AS [ReferenceProductID],
[Extent1].[ConditionInfo] AS [ConditionInfo]
FROM [dbo].[ProductTOC] AS [Extent1]
WHERE [Extent1].[ProductVersionID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=177
,有两个单独的查询,如下所示:
productTOC
和
exec sp_executesql N'SELECT
[Extent1].[ID] AS [ID],
...
[Extent1].[ProductCode] AS [ProductCode]
FROM [dbo].[Product] AS [Extent1]
WHERE [Extent1].[ID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=79
如果我在SQL中执行此操作,则只需连接表并在单个查询中检索所需的内容。谁能告诉我为什么我要进行很多小的查找?谢谢。
答案 0 :(得分:1)
如果您只是尝试将查询置于其他查询之外怎么办?喜欢
private static IEnumerable<CompositeTocDataItem> GetCompositeTocData(P42Entities ctx, int userID, RSPlatform.Data.Core.ProductVersion productVersion)
{
var up = productVersion.ProductTOCs.ReferenceProduct?.UserProducts.Where(UP=>UP.UserID == userID).FirstOrDefault(); //do it HERE ..so it hit the DB only once..and then you work in memory
return from toc in productVersion.ProductTOCs
orderby toc.Position
select new CompositeTocDataItem()
{
Position = toc.Position,
Level = toc.Level,
Name = toc.Name,
ReferenceProductID = toc.ReferenceProductID,
RefCode = toc.RefCode,
ConditionInfo = toc.ConditionInfo,
LastCompletedDate = up?.LastCompletedDate,
Score = up?.Score,
ScoreStatus = up?.ScoreStatus ?? "N",
};
}
希望它对您有帮助