C Sharp - Linq - DefaultIfEmpty

.DefaultIfEmpty

Sample

1
2
3
4
5
6
7
8
9
var query =
( from c in _context.Categories
join p in _context.Programs on c.Id equals p.CategoryId into Programs
from program in Programs.DefaultIfEmpty() where program.IsDeleted == false
join r in _context.Permits on c.Id equals r.CategoryId into Permits
from permit in Permits.DefaultIfEmpty() where permit.IsDeleted == false
where c.Id == id
select new { program, permit }
).Distinct();

DefaultIfEmpty is only useful if you provide a default object. in this case that is used here, if there are no programs, then ‘program’ will be null, and program.IsDeleted will throw exception.