Reputation: 754
Is it really possible to cause a NullReferenceException
on a join statement even if it has the DefaultIfEmpty()
code?
var getWorkerList = (from a in workerList
join ps in db.ProjectStatus on a.StatusId equals ps.StatusId into hjps
from ps in hjps.DefaultIfEmpty()
join psc in db.StatusColor on ps.StatusCode equals psc.StatusCode into hjpsc
from psc in hjpsc.DefaultIfEmpty()
join lu in db.LOOKUPS on psc.StatusColorID equals lu.LOOKUPS_ID into hjlu
from lu in hjlu.DefaultIfEmpty()
select new WorkerModel()
{
FullName = a.FullName
,Color = lu.LOOKUPS_Code
}).OrderBy(a => a.WorkerId).ToList();
Here is where I get the NullReferenceException
Error :
join lu in db.LOOKUPS on psc.StatusColorID equals lu.LOOKUPS_ID into hjlu
from lu in hjlu.DefaultIfEmpty()
When adding this join statement I get the error. Please help.
Upvotes: 1
Views: 1471
Reputation: 2083
you are using 'left join' instead of 'join' by '.DefaultIfEmpty()'
so you have to correct select statement: replace 'Color = lu.LOOKUPS_Code' with this: 'Color = lu == null ? "" : lu.LOOKUPS_Code'.
also you are able to use a different overload of '.DefaultIfEmpty()' to set a replacement instead of 'null', so then the select statement wouldn't throw an exception
Upvotes: 1
Reputation: 77304
.DefaultIfEmpty()
returns a sequence with a single default value if the original source is empty.
It will still throw a null reference exception, if the original source is null.
Upvotes: 4