2014-01-27 122 views
1

我正在努力處理涉及左連接的Linq查詢。這裏是我試圖轉換的SQL:與Linq的多個左連接

SELECT EmailStats.EmailAddress, EmailVoting.DateAdded, EmailVoting.ResponseText, 
     EmailStats.DateSent, EmailAlerts.Name, UserDetails.EmployeeNumber 
FROM EmailAlerts 
INNER JOIN EmailStats 
    ON  EmailAlerts.EmailAlertID = EmailStats.EmailAlertID 
INNER JOIN UserDetails 
    ON  EmailStats.UserId = UserDetails.UserId 
LEFT OUTER JOIN EmailVoting 
    ON  EmailAlerts.EmailAlertID = EmailVoting.EmailAlertID 
    AND EmailVoting.UserId = EmailStats.UserId 
Where EmailAlerts.EmailAlertID = 43 AND EmailStats.IsTestSend = 0 

如果行不存在,SQL將使用EmailVoting字段返回正確的數據。下面是LINQ我目前有:

from ea in db.EmailAlerts 
join es in db.EmailStats on ea.EmailAlertID equals es.EmailAlertID 
join ud in db.UserDetails on es.UserId equals ud.UserId 
join ev in db.EmailVoting on ea.EmailAlertID equals ev.EmailAlertID into vm 
from v in vm.DefaultIfEmpty() 
join ev in db.EmailVoting on es.UserId equals ev.UserId into udItems 
from u in udItems.DefaultIfEmpty() 
where v.EmailAlertID == emailAlertID 

我的想法是LINQ相同,則無法正確顯示實際上是在顯示與不同EmailAlertID的條目。任何人都可以看到我可能會出錯的地方?

感謝

回答

3

試試這個:

from ea in db.EmailAlerts 
join es in db.EmailStats on ea.EmailAlertID equals es.EmailAlertID 
join ud in db.UserDetails on es.UserId equals ud.UserId 
join ev in db.EmailVoting on new {ev.EmailAlertID, ev.UserId} equals new {ea.EmailAlertID, es.UserId} into vm 
from v in vm.DefaultIfEmpty() 
where v.EmailAlertID == emailAlertID 
+0

哈姆雷特您好,感謝您的回答。不幸的是,這並沒有產生與我的結果不同的結果。我已經使用了一種避免左連接的方法,只是比較C#中的2個列表。這不是一個巨大的應用程序,所以沒有這樣做的重大性能損失,所以這是我選擇的。非常感謝,但。 –