views:

20871

answers:

4

I'm writing a linq to sql statement & I'm just after the standard syntax for a normal inner join with an 'on' clause in C#.

ie how do you represent this in LINQ to SQL?:

select * from table1 
inner join table2 on table1.field table2.field

EDIT: Real query to get all contacts for a dealer:

select DealerContact.*
from Dealer 
    inner join DealerContact on Dealer.DealerID = DealerContact.DealerID
+24  A: 

It goes something like:

from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}

It would be nice to have sensible names and fields for your tables for a better example. :)

Update

I think for your query this might be more appropriate:

var dealercontacts = from contact in DealerContact
                     join dealer in Dealer on contact.DealerId equals dealer.ID
                     select contact;

Since you are looking for the contacts, not the dealers.

Jon Limjap
+8  A: 

Use Linq Join operator:

var q =  from d in Dealer
         join dc in DealerConact on d.DealerID equals dc.DealerID
         select dc;
aku
+5  A: 
var results = from c in db.Companies
              join cn in db.Countries on c.CountryID equals cn.ID
              join ct in db.Cities on c.CityID equals ct.ID
              join sect in db.Sectors on c.SectorID equals sect.ID
              where (c.CountryID == cn.ID) && (c.CityID == ct.ID) && (c.SectorID == company.SectorID) && (company.SectorID == sect.ID)
              select new { country = cn.Name, city = ct.Name, c.ID, c.Name, c.Address1, c.Address2, c.Address3, c.CountryID, c.CityID, c.Region, c.PostCode, c.Telephone, c.Website, c.SectorID, Status = (ContactStatus)c.StatusID, sector = sect.Name };


return results.ToList();
herste
Hi,Can you tell me please what is this part is about? Status = (ContactStatus)c.StatusIDI am interested expecially in the fragment: (ContactStatus)c.StatusIDRegardsMariusz
aristo
@aristo - looking at the code, I'm guessing that `ContactStatus` is really an enum, and `c.StatusID` isn't really an ID, but the numeric value of the enum. If I'm right, `(ContactStatus)c.StatusID` is really just casting an integer to an enum.
Joel Mueller
+2  A: 

And because I prefer the expression chain syntax, here is how you do it with that:

var dealerContracts = DealerContact.Join(Dealer, 
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);
Clever Human