我正在努力解决涉及左连接的Linq查询。这是我想要转换的SQL:
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字段为null。以下是我目前拥有的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的条目。谁知道我可能会出错?
由于
答案 0 :(得分: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