LINQ中的多对多查询

时间:2012-10-23 16:58:45

标签: c# linq

我有4张桌子:

  

地址 - 地址ID,城市,地址,ZipCode

     

OBAddress - OBID,AddressID

     

OB - OBID

     

州 - StateID,StateAbbreviation

如何加入多对多关系中的三个表?我试过了:

var recordsPhysicalAddress = ( from a in db.Addresses
    join oba in db.obAddresses on a.AddressID equals oba.AddressID
    join ob in db.obAddresses on oba.obID equals passedinID
    join s in db.States on a.StateID equals s.StateID
    where oba.obID == ob.obID
    && a.AddressTypeID == '5' //5 is records physical address
    select new
    {
        a.Address1, 
        a.City, 
        a.StateID,
        s.StateAbbreviation,
        a.ZipCode
    }).FirstOrDefault();

1 个答案:

答案 0 :(得分:1)

var query = (from a in db.Addresses
             join oba in db.obAddresses on a.AddressID equals oba.AddressID
             // do not join with db.obAddresses again
             join s in db.States on a.StateID equals s.StateID
             where oba.obID == passedinID // filter here
                   && a.AddressTypeID == '5'
             select new {
                   a.Address,
                   a.City,
                   a.StateID,
                   s.StateAbbreviation,
                   a.ZipCode
             }).FirstOrDefault();

我在评论中添加了一些评论来查询。但仍然想知道为什么你提到了有问题的桌子?