2014-12-01 51 views
0

我試圖重新寫了下面的SQL LEFT OUTER使用實體框架6 JOIN查詢:實體框架6 - 外連接和方法語法查詢

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兩個DbSet對象通過實體框架可用,在連接使用多列。

我也很確定這不會做正確的左外部連接,即使我沒有收到編譯器錯誤;我懷疑我需要在某個地方以某種方式涉及DefaultIfEmpty()方法。獎勵積分,如果你也可以幫助我。

更新#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; 
} 

回答

0

請問您可以試試這個解決方案嗎?我不確定結果:(

(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();