linq多连接在某些空表中不起作用

时间:2014-07-14 15:30:43

标签: c#

您好我使用4张桌子..

有时它没有此表中的信息(教育或地址或证书) 所以结果是空的.. 如果有信息怎么说? 示例

**PersonTable**

PersonId    PersonName
 1453           george

**Certificate Table**

CertificateId PersonId  CertificateName  ( 0 records)


**Addres Table**

AddresId  PersonId    Adress
1           1453        ......
2           1453        .....
3           1453        ......
4           1453       ......
5           1453       ........

**EducationTable**

EducationId   PersonId   Education
1               1453          school name


**BankTable**

BankId       PersonId         Bank  ( 0 records )


Person table = 1 records
Certificates = 0 records
Address = 5 records
Education = 1 records
Bank = 0 records

var query = (from p in DbEntities.t_Person
                         join q in DbEntities.t_Address on p.PersonId equals q.addressId
                         join n in DbEntities.t_Education on p.PersonId equals n.EduId
                         join j in DbEntities.t_Certificate on p.PersonId equals j.CertificateId
                         join f in DbEntities.t_BankAccount on p.PersonId equals f.BankId
                         where p.PersonId.Equals(id)
                         select new { p, q, n, j, f }).FirstOrDefault();

返回查询值null,

我不明白为什么这些价值观?

Person table = 1 records 
Address = 5 records
Education = 1 records

我想到了,但没有

var query = (from p in DbEntities.t_Person
                  where p.PersonId.equlas(id)
                  select p).singleOrDefault();

query = from p in dbEntities.Address
              WHERE P.AddressId.equlas(query.PersonId)
             select p;

1 个答案:

答案 0 :(得分:0)

这是因为您正在进行INNER JOIN,只有在满足所有加入条件的情况下才会返回记录!看起来你想要做一个LEFT JOIN,它将返回左表中的所有行,而右表中它将返回找到的任何记录,否则返回null。 Here是一个很好的帖子,用图解释不同类型的连接!

Linq-to-Entities进行左连接的方式是DefaultIfEmpty()。有关使用示例,请参阅MSDN