2014-10-07 73 views
1

檢索所有記錄我曾經做過一個內部聯接,它僅顯示與以下查詢匹配的記錄: -的LINQ - INNER JOIN不是從左表

var data = from t1 in ctx.tblEmp 
      join t2 in ctx.tblHelp 
       on t1.Field equals t2.Fld 
      where t1.Id == Id && 
       t2.Id == Id 
      select new Settings { Master = t1.Labelname, OrderNo = t2.OrderNo}; 

我想從tblEmp &唯一匹配的記錄中的所有記錄從tblHelp

如何做到這一點?

+4

這是一個左連接,然後不是一個內部聯接。你可以在SO上搜索這個。 – 2014-10-07 11:05:14

+0

http://stackoverflow.com/questions/5537995/entity-framework-left-join – AlexFoxGill 2014-10-07 11:32:08

回答

2

用作

var data = from t1 in ctx.tblEmp 
     join t2 in ctx.tblHelp 
      on t1.Field equals t2.Fld into u 
      from t2 in u.DefaultIfEmpty() 
     where t1.Id == Id && 
      t2.Id == Id 

     select new Settings { Master = t1.Labelname, OrderNo = t2.OrderNo}; 

試試這個

var data = from t1 in ctx.tblEmp 
     join t2 in ctx.tblHelp 
      on t1.Field equals t2.Fld into u 
      from t2 in u.DefaultIfEmpty() 
     where t1.Id == Id 
     orderby columnname // Added Order By 
     select new Settings { Master = t1.Labelname, OrderNo = t2.OrderNo==null ?"":t2.OrderNo}; 
+0

仍給我只匹配的記錄。 – Anup 2014-10-07 11:25:39

+0

我得到錯誤'鑄造值類型'System.Int32'失敗,因爲物化值爲空。結果類型的泛型參數或查詢必須使用可空類型.' – Anup 2014-10-07 11:43:08

+0

@Anup立即嘗試檢查null條件 – Amit 2014-10-07 11:45:12

1
var query = from t1 in ctx.tblEmp 
        join t2 in ctx.tblHelp on t1 equals t2.Fld into tempGroup 
        from subpet in tempGroup.DefaultIfEmpty() 
        select new { t1.Labelname, OrderNo = (subpet == null ? String.Empty : subpet.OrderNo) };