简体   繁体   中英

LINQ Query with multiple joins on fk tables

I need to get contacts that are related to a given business and a given contactcode. The contact can have multiple contactcodes.

This is as close as I've been able to get - any help is appreciated...

    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;

This is the equivalent t-sql I'm after...

 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  
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();     
}

you can do like this:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM