2014-11-16 92 views
1

我有4个表格;Linq Lambda多个表格(4个表格)LEFT JOIN

TMain >> MainId (PK) 

T1 >> T1_Id, MainId, X (PK and FK) X is decimal 

T2 >> T2_Id, MainId, X (PK and FK) X is decimal 

T3 >> T3_Id, MainId, X (PK and FK) X is decimal 

这里SQL输出;

SELECT TMain.*, (ISNULL(T1.X,0) + ISNULL(T2.X,0) + ISNULL(T3.X,0)) AS TOTAL FROM TMain 

LEFT OUTER JOIN T1 ON TMain.MainId = T1.MainId 

LEFT OUTER JOIN T2 ON TMain.MainId = T2.MainId 

LEFT OUTER JOIN T3 ON TMain.MainId = T3.MainId 

我如何写LINQ LAMDA

var AbbA = MyContext.TMain 
        .GroupJoin(
         MyContext.T1, 
         q1 => q1.TMainId, 
         q2 => q2.TMainId, 
         (x, y) => new { A = x, T1_A = y }) 
          .SelectMany(
          xy => xy.T1_A.DefaultIfEmpty(), 
          (x, y) => new { A = x.A, T1_A = y }) 
        .GroupJoin(
         MyContext.T2, 
         q1 => q1.A.TMainId, 
         q2 => q2.TMainId, 
         (x, y) => new { A = x, T2_A = y }) 
          .SelectMany(
          xy => xy.T2_A.DefaultIfEmpty(), 
          (x, y) => new { A = x.A, T2_A = y }) 
        .GroupJoin(
         MyContext.T3, 
         q1 => q1.A.A.TMainId, 
         q2 => q2.TMainId, 
         (x, y) => new { A = x, T3_A = y }) 
          .SelectMany(
          xy => xy.T3_A.DefaultIfEmpty(), 
          (x, y) => new { A = x.A, T3_A = y }) 
        .Select(q => new 
        { 
         TMainId = q.A.A.A.TMainId, 
         Total = (q.T3_A.X == null ? 0 : q.T3_A.X) + 
           (q.A.T2_A.X == null ? 0 : q.A.T2_A.X) + 
           (q.A.A.T1_A.X == null ? 0 : q.A.A.T1_A.X), 
        }).ToList(); 

所以我想要访问

我写q.A.A.T1_A.X或q.A.A.A. T1字段或TMain领域in linq select

这是真的吗?或者有最简单的方法?

+0

尽量参见[101个LINQ样品:加入运营商(HTTP:// MSDN。 microsoft.com/ru-ru/vstudio/ee908647.aspx#leftouterjoin) – Grundy

+1

嗨,感谢您的回复我发现了一些答案,但不是LAMBDA http://stackoverflow.com/questions/16049586/linq-query-to-join -4-表 – AbbA

回答

0

我现在不能测试是否会工作,但有时你可以写群组加入类似(如果你指望0或N从T1寄存器):

.GroupJoin(MyContext.T1, 
    q1 => q1.TMainId, 
    q2 => q2.TMainId, 
    (x, y) => new { A = x, T1_A = y.DefaultIfEmpty() }) 

或者(如果你希望从T1 0或1寄存器)

.GroupJoin(MyContext.T1, 
    q1 => q1.TMainId, 
    q2 => q2.TMainId, 
    (x, y) => new { A = x, T1_A = y.FirstOrDefault() }) 

它总是取决于你喜欢什么返回下一个拉姆达,在这种情况下你不需要的SelectMany()。但是如果你不能相应地映射表之间的关系,那么这段代码将成为你可以用linq/lambda获得的最简单的左连接。

,如果你映射表TMain和T1与“HasOptional”之间的关系可以简化,如:

modelBuilder.Entity<T1>() 
      .HasOptional(x => x.TMain) 
      .WithMany(y => y.T1s) 
      .HasForeignKey(x => x.TMaidId); 

的“HasOptional()”显示了实体框架,这种关系是可选的,于是左手JOIN将用于装入查询。如果使用“HasRequired()”,将使用JOIN。

所以,你可以使用include():

var AbbA = MyContext.TMain 
    .Include(x => x.T1s) 

左连接T1和T2:

var AbbA = MyContext.TMain 
    .Include(x => x.T1s.Select(y => y.T2s))