2016-03-03 48 views
-1

基於下面的SQL,我正努力嘗試在LINQ或方法語法中編寫LINQ語句。將SQL轉換爲LINQ,帶有多個連接和一個謂詞

SELECT vr.* 
FROM VisualReport vr 
JOIN VisualReportRoleList vrl ON vr.VisualReportSK = vrl.VisualReportSK 
JOIN Role r ON vrl.RoleSK = r.RoleID 
JOIN UserRoleList url ON r.RoleID = url.RoleID 
JOIN Users u ON url.UserID = url.UserID 
WHERE u.ID = 1 

我試過很多東西,但沒有運氣。我打算在這裏發佈一些內容,但這只是讓這篇文章看起來很雜亂。

任何人都可以幫助我嗎?

+0

有一些相當不錯的工具,可以幫助你做到這一點..做一個谷歌搜索'LinqPad'看看有沒有免費的下載試用版 – MethodMan

回答

0

加入模式是這樣的

帕拉姆1.要加入就行了,左邊

參數2鍵(在呼籲加入什麼),

帕拉姆3.關鍵在右邊(你加入的是什麼),

參數4.是結果選擇器如何選擇結果。

db.VisualReposts.Join(db.VisualRepostRoleLists, 
         vr => vr.VisualReportSK, 
         vrl => vrl.VisualReportSK 
         (vr, vrl) => new { vr, vrl}).Join(db.Roles, 
                 vrj => vrj.vrl.RoleSK, 
                 r => r.RoleID, 
                vrj, r => new {vr = vrj.vr, 
                   vrl = vrj.vrl, 
                   role = r}) 

    //follow the same patter for the rest of the joins. 
    // Also add your where clause, it might be a better idea to start 
    //from the users table so you can filter first 

但是,如果一切正確外鍵,您不需要進行連接,您可以訪問ICollections。如果你可以或讓他們外鍵,你可以像這樣訪問它們

var user = db.Users.Where(u => u.id == 1); 

//everything should have an icollection now so you can access via 
//user.UserRoleList.Roles ect or what ever you need 
0

簡單的一對一轉換。 LinqPad應該將其轉換爲與您的查詢等效。

var result = (from vr in VisualReport 
    join vrl in VisualReportRoleList on vr.VisualReportSK equals vrl.VisualReportSK 
    join r in Role on vrl.RoleSK equals r.RoleID 
    join url in UserRoleList on vrl.RoleSK equals url.RoleID 
    join u in Users on url.UserID equals u.UserID 
    where u.ID == 1 
    select vr).ToList();