2016-02-12 71 views
0

我試圖用LINQ將2個表連接到另外2個表上,但我似乎無法弄清楚這是如何完成的。使用LINQ在2個其他表上進行1表連接

我可以使它在Visual Studio中編寫純SQL語句,我只是不確定如何將其轉換爲LINQ。

這裏是我的SQL語句:

SELECT c.CustomerId, c.CustomerName, pw.Number, pc.Number FROM Customers as c 
LEFT JOIN Tasks as k ON k.Id = c.Task_Id 
LEFT JOIN Workers as w ON w.Id = k.Worker_Id 
LEFT JOIN PersonNumbers as pw ON pw.Person_Id = w.Id 
LEFT JOIN Chiefs as ch ON ch.Id = k.Chief_Id 
LEFT JOIN PersonNumbers as pc ON pc.Person_Id = ch.Id 

也許這需要一些解釋。

我們有一堆客戶和這些客戶可以有一些任務。在一項任務中,您將有工作人員負責人。在PersonNumbers表中,我有一些關於工作人員首長的一些額外信息,這是我需要的信息。

任何幫助表示讚賞!提前致謝。

+1

這是一個簡單的查詢,您應該使用能夠把它寫在LINQ [這](https://msdn.microsoft.com/en-us/library/bb397927.aspx)。 –

+0

類似的實現檢查是否有幫助http://stackoverflow.com/questions/5571861/joining-two-tables-using-linq – Maverick

+1

你可以在Linq中使用'join',但最好使用導航屬性,假設你的實體擁有他們。 https://coding.abel.nu/2012/06/dont-use-linqs-join-navigate/ – juharr

回答

1

假設你所有的連接都是基於外鍵的,你應該可以做如下的事情,這些外鍵會導致實體的導航屬性。 DefaultIfEmpty是什麼使所有的東西左加入。

var results = from c in db.Customers 
       from k in c.Tasks.DefaultIfEmpty() 
       from w in k.Workers.DefaultIfEmpty() 
       from pw in w.Persons.DefaultIfEmpty() 
       from ch in k.Chiefs.DefaultIfEmpty() 
       from pc in ch.Persons.DefaultIfEmpty() 
       select new 
       { 
        c.CustomerId, 
        c.CustomerName, 
        pw.Number, 
        pc.Number 
       }; 

如果您沒有導航屬性,那麼您將不得不使用join

var results = from c in db.Customers 
       join xk in db.Tasks on xk.Id equals c.Task_Id 
       from k in xk.DefaultIfEmpty() 
       join xw in db.Workers on xw.Id equals k.Worker_Id 
       from w in xw.DefaultIfEmpty() 
       join xpw in db.Persons on xpw.Person_Id equals w.Id 
       from pw in xpw.DefaultIfEmpty() 
       join xch in db.Chiefs on xch.Id equals k.Chief_Id 
       from ch in xch.DefaultIfEmpty() 
       join xpc in db.Persons on xpc.Person_Id euals ch.Id 
       from pc in xpc.DefaultIfEmpty() 
       select new 
       { 
        c.CustomerId, 
        c.CustomerName, 
        pw.Number, 
        pc.Number 
       }; 
相關問題