[英]Linq query to display the values from two tables even if one of the table doesn't have any corresponding record
I'm working on a project where we have two tables People
and Emails
. 我正在一个项目中,我们有两个表People
和Emails
。 I wanted to display the People
records with his Emails
whether Emails
table have the person's emails or not. 无论Emails
表中是否包含该人的电子邮件,我都想在其Emails
显示People
记录。
I tried with the below query but it displays the record only when the Person's Email rocord is available in table. 我尝试使用以下查询,但仅在表中有“人员的电子邮件”信息时才显示记录。
_db.People.Join(_db.Emails, e => e.PersonId, p=> p.PersonId, (e, p) => new { e, p }).Where(x => x.p.PersonId == personId).Select(x => new { Id = x.p.PersonId, x.p.FirstName, x.p.LastName, x.p.Gender, x.e.EmailAddress})OrderBy(x => x.Id).ToList();
Can anyone suggest how would I display all People which have or doesn't have the EmailAddress in Emails
table. 谁能建议我如何显示“ Emails
表中所有具有或没有Emails
。
Thank You! 谢谢!
So you want a Left Join using Linq: 因此,您需要使用Linq进行左联接:
var results = (from p in _db.People
join e in _db.Emails
on p.PersonId equals e.PersonId into LeftJoin
from res in LeftJoin.DefaultIfEmpty()
select new
{
Id = p.PersonId,
FirstName = p.FirstName,
LastName = p.LastName,
Gender = p.Gender,
Email = res == null ? null : res.EmailAddress
}).ToList();
Hope this works fine. 希望这能正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.