对fk个表进行多个连接的LINQ查询

本文关键字:连接 LINQ 查询 fk | 更新日期: 2023-09-27 18:04:38

我需要获得与给定业务和给定contactcode相关的联系人。联系人可以有多个contactcode。

这是我所能得到的最接近的——任何帮助都是感激的…

    int bid = 10;
    var sendto = from businesscontact in db.businesscontacts.Where(bus => bus.businessid == bid).Include(bc => bc.contact where contact.contactscontactcodes.contactcodesid.Contains(55)) select r.email;

这是等价的t-sql,我在…

 SELECT  contacts.email
    FROM   businesscontacts 
    INNER JOIN contacts ON businesscontacts.contactsid = contacts.contactsid 
    INNER JOIN contactscontactcodes ON contacts.contactsid = contactscontactcodes.contactsid 
where contactscontactcodes.contactcodesid = @cid 
AND businesscontacts.businessid = @bid  

对fk个表进行多个连接的LINQ查询

using(EntityClass entities = new EntityClass())
{
var email = 
      (from biz in entities.BusinessContacts
      where biz.businessid = bid
      from codes in entities.ContactsContactCodes
      where codes.contactcodesid = cid
      from c in entites.Contacts
      where c.contactsid == codes.contactsid && c.contactsid == biz.contactsid
      select c.email).FirstOrDefault();     
}

你可以这样做:

int cid = 1;
int bid = 2;
var sendto = from businesscontact in db.businesscontacts
             join contacts in db.contacts 
             on businesscontact.contactsid equals contacts.contactid
             join contactscontactcodes in db.contactscontactcodes  
             on contacts.contactsid equals contactscontactcodes.contactsid
             where contactscontactcodes.contactcodesid = cid
             && businesscontacts.businessid = bid
             select contact.email;