左外连接未兑现

时间:2019-07-03 17:10:34

标签: c# entity-framework

我们有以下EF代码:

    var qry =
            from c in db.Contacts

            join comp in db.Companies on c.CompanyId equals comp.CompanyId
                into compLeft
            from cj in compLeft.DefaultIfEmpty()

            select new CompleteUserDlModel
            {
                CompanyName = cj.Company1,
                CompanyId = c.CompanyId
            };

生成此SQL

SELECT 
    [Extent1].[CompanyId] AS [CompanyId], 
    [Extent2].[Company] AS [Company]
    FROM  [dbo].[Contacts] AS [Extent1]
    INNER JOIN [dbo].[Company] AS [Extent2] ON [Extent1].[CompanyId] = [Extent2].[CompanyId]

但我们实际上想要

SELECT 
    [Extent1].[CompanyId] AS [CompanyId], 
    [Extent2].[Company] AS [Company]
    FROM  [dbo].[Contacts] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Company] AS [Extent2] ON [Extent1].[CompanyId] = [Extent2].[CompanyId]

请问有人指出我们做错了吗?

C#EF(即LEFT OUTER JOIN in LINQ)中左外部联接上的所有引用均指向我们使用的语法。显然,我们缺少了一些东西。

2 个答案:

答案 0 :(得分:2)

  

请问有人指出我们做错了吗?

可能您有Contact.CompanyId类型的int而不是int?,使其成为必需的属性,因此EF假定您在生成查询时具有参照完整性。

但是,与往常一样,LINQ中的left join有着不好的代码味道,并且几乎总是可以通过查询目标实体并遍历其导航属性来替换。 EG:

 from c in db.Contacts
 select new
 {
     CompanyName = c.CompanyId.HasValue?c.Company.CompanyName : null,
     CompanyId = c.CompanyId
 };

答案 1 :(得分:0)

var qry =
            from c in db.Contacts

            join comp in db.Companies on c.CompanyId equals comp.CompanyId
                into compLeft
            from cj in compLeft.DefaultIfEmpty()

            select new CompleteUserDlModel
            {
                CompanyName = cj.Company1,
                CompanyId = c?.CompanyId ?? String.Empty
            };