实体框架6 - 外部联接和方法语法查询

时间:2014-12-01 16:01:26

标签: c# linq entity-framework-6 linq-method-syntax

我尝试使用Entity Framework 6重新编写以下SQL LEFT OUTER JOIN 查询:

select tblA.*, tblB.*
from dbo.TableA tblA left outer join dbo.TableB tblB on 
    tblA.Student_id=tblB.StudentId and tblA.other_id=tblB.OtherId
where tblB.Id is null

这是我当前的C#代码:

using (var db = EFClass.CreateNewInstance())
{
    var results = db.TableA.GroupJoin(
        db.TableB,
        tblA => new { StudentId = tblA.Student_id, OtherId = tblA.other_id },
        tblB => new { tblB.StudentId, tblB.OtherId },
        (tblA, tblB) => new { TableAData = tblA, TableBData = tblB }
    )
    .Where(x => x.TableBData.Id == null)
    .AsNoTracking()
    .ToList();

    return results;
}

以下是编译错误:

  

无法从用法推断出类型参数。尝试指定   显式的类型参数。

简而言之:我需要 OUTER JOIN 通过Entity Framework提供的两个 DbSet 对象,在连接中使用多个列。

即使我没有收到编译错误,我也相当肯定这不会正确地执行 LEFT OUTER JOIN ;我怀疑我需要以某种方式涉及DefaultIfEmpty()方法。如果你能帮我解决这个问题,也可以获得奖励。

UPDATE#1 :如果我在联接中使用强类型,它是否有效...它是无法处理匿名类型,还是我做错了什么?

public class StudentOther
{
    public int StudentId { get; set; }
    public int OtherId { get; set; }
}

using (var db = EFClass.CreateNewInstance())
{
    var results = db.TableA.GroupJoin(
        db.TableB,
        tblA => new StudentOther { StudentId = tblA.Student_id, OtherId = tblA.other_id },
        tblB => new StudentOther { StudentId = tblB.StudentId, OtherId = tblB.OtherId },
        (tblA, tblB) => new { TableAData = tblA, TableBData = tblB }
    )
    .Where(x => x.TableBData.Id == null)
    .AsNoTracking()
    .ToList();

    return results;
}

1 个答案:

答案 0 :(得分:-1)

你能试试这个解决方案吗?我不确定结果:(

(from tblA in dbo.TableA
join tblB in dbo.TableB on new { tblA.Student_id, tblA.other_id } equals new { blB.StudentId, tblB.OtherId }
into tblBJoined
from tblBResult in tblBJoined.DefaultIfEmpty()
where tblBResult.Id == null
select new {
    TableAData = tblA,
    TableBData = tblB
}).ToList();