简体   繁体   中英

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 . I wanted to display the People records with his Emails whether Emails table have the person's emails or not.

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.

Thank You!

So you want a Left Join using 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.

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