Left-Outer-使用Linq / EntityFramework连接到同一个表

时间:2017-07-19 17:46:13

标签: entity-framework linq

我需要在同一个表中创建一个left-outer-join:

SELECT Top(20) s.Id as ParentId, CASE WHEN cr.Id IS NOT NULL THEN 'False' ELSE 'True' END AS HasChangeRequest
FROM [Platos.PRM.Dev].[dbo].[Section] s
left outer join [Section] cr on cr.ParentSectionId = s.Id

为此,我写了以下Linq声明:

var query = from section in this.prmDbContext.Sections
        join changeRequest in this.prmDbContext.Sections.Where(x => x.ParentSection != null && !x.IsInactive) on section.Id equals changeRequest.ParentSection.Id into changeRequestJoin
        from changeRequest in changeRequestJoin.DefaultIfEmpty()
        select new 
        {
            Id = section.Id,
            HasChangeRequest = changeRequest != null
        };

var result = query.Take(20).ToList();

linq语句可以正常运行并提供正确的结果,但速度很慢。

SQL语句:几毫秒 - LINQ语句:5秒

有谁能告诉我,为什么这个linq语句的表现不好?

谢谢!

更新 添加导航属性(ChangeRequests)后,我将查询更新为以下linq语句:

var query = from section in this.prmDbContext.Sections        
select new 
{
    Id = section.Id,
    HasChangeRequest = section.ChangeRequests.Any()
};
var result = query.Take(20).ToList();

现在EntityFramework创建了以下sql查询:

SELECT 
[Limit1].[C1] AS [C1], 
[Limit1].[Id] AS [Id], 
[Limit1].[C2] AS [C2]
FROM ( SELECT TOP (20) 
    [Extent1].[Id] AS [Id], 
    1 AS [C1], 
    CASE WHEN ( EXISTS (SELECT 
        1 AS [C1]
        FROM [dbo].[Section] AS [Extent2]
        WHERE [Extent1].[Id] = [Extent2].[ParentSectionId]
    )) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C2]
    FROM [dbo].[Section] AS [Extent1]
)  AS [Limit1]

现在查询速度更快,但仍然比本机sql查询中的left-outer-join慢。那么有可能优化linq语句吗?

0 个答案:

没有答案