Tuesday, October 3, 2017

Use .DefaultIfEmpty() to make a left join with LINQ.

A left join:

public IQueryable<Feline> GetOtherCats()
{
   var q = from c in DbContext.Cats.Where(c => c.Name != "Mango")
from d in DbContext.Dogs.Where(d => d.Id == c.Enemy).DefaultIfEmpty()
select new Feline()
{
   Name = c.Name,
   RemainingNumberOfLives = c.RemainingNumberOfLives,
   Enemy = c.Enemy == null ? null : d.Name
};
   return q;
}

 
 

This is contrast is an inner join:

public IQueryable<Feline> GetOtherCats()
{
   var q = from c in DbContext.Cats.Where(c => c.Name != "Mango")
from d in DbContext.Dogs.Where(d => d.Id == c.Enemy)
select new Feline()
{
   Name = c.Name,
   RemainingNumberOfLives = c.RemainingNumberOfLives,
   Enemy = d.Name
};
   return q;
}

No comments:

Post a Comment