I have the following LINQ query
var categories = (from c in context.Categories
join pc in context.ProductCategories
on new { Id = c.CategoryId, ProductId = 12 }
equals new { Id = pc.CategoryId, ProductId = pc.ProductId }
into productCategories
from pc in productCategories.DefaultIfEmpty()
select new ViewModel
{
CategoryId = c.CategoryId,
Category = c.Name,
Selected = (pc.CategoryId == null) ? false : true
}).ToList();
This gives me a compiler warning at pc.CategoryId == null
saying it will always be false as CategoryId
is of type Int and not nullable. But because of left outer join it comes as null
from database.
If I ignore the warning everything works as expected. Is it okay to this way or is there a better way to do this?
This gives me a compiler warning at pc.CategoryId == null saying it will always be false as CategoryId is not nullable. But because of left outer join it comes as null from database.
No, pc
might be null - but pc.CategoryId
would logically just throw an exception if pc
is null. (As noted in comments, it may not actually do so, due to the query being translated into SQL. But I try to write LINQ code which is logically correct as well as happening to work :)
Don't forget that DefaultIfEmpty()
returns a sequence that is either the original sequence of elements, or a sequence with one element which is the default for the element type. If that element type is a class (which I expect it is here) the default value is null
, which is why pc
would be null if there were no matches.
It sounds like you want:
Selected = pc != null
See more on this question at Stackoverflow