C#Linq:添加另一个连接条件

时间:2013-07-19 06:14:15

标签: c# sql linq

我有一个问题:

// Query: gets recipients that have not been sent yet....
var query = (from rec in ent.Recipients 
join ch in ent.CampaignHistories on rec.RecipientID equals ch.RecipientID
into chl
from x in chl.DefaultIfEmpty().Where(xx => !xx.RecipientID.HasValue)

select new BRecipient()  
 {
   Email = rec.Email,
   Name = rec.Name,
   RecipientID = rec.RecipientID
 }).Take(remaining);

这基本上会在SQL中进行左连接,相当于:

Select * FROM            Recipients AS R LEFT OUTER JOIN
                         CampaignHistory AS H ON R.RecipientID = H.RecipientID 
WHERE        (H.RecipientID IS NULL)

我想要的是:

Select * FROM            Recipients AS R LEFT OUTER JOIN
                             CampaignHistory AS H ON R.RecipientID = H.RecipientID
AND H.CampaignID <> 21 
    WHERE        (H.RecipientID IS NULL)

如何创建LINQ?

2 个答案:

答案 0 :(得分:1)

我相信会:

join ch in ent.CampaignHistories.Where(x=>x.CampaignID != 21)
    on rec.RecipientID equals ch.RecipientID

但说实话,我看不到你想要做什么。你为什么不这样做:

from rec in ent.Recipients
where !ent.CampaignHistories
          .Any(x=>x.RecipientID == rec.RecipientID && x.CampaignID != 21)
select ...

答案 1 :(得分:1)

var query = (from rec in ent.Recipients
             join ch in ent.CampaignHistories.Where(xx => !xx.RecipientID.HasValue && xx.CampaignID != 21) on rec.RecipientID equals ch.RecipientID
             into chl
             from x in chl.DefaultIfEmpty()

             select new BRecipient()
             {
                 Email = rec.Email,
                 Name = rec.Name,
                 RecipientID = rec.RecipientID
             }).Take(remaining);