Reputation: 275
I am trying to use left join with multiple tables which was working fine until one more table was in introduced (tb4) as now it is throwing object reference not set.
Before tb4 was introduced, i get 3 records from earlier resultset which have stateId = null. But as I am using the same id(i.e stateid) in my last join which is coming to be null in aa ie ( aa.StateId). so, it is throwing exception. Can we handle this thing while applying join that if a joining key comes to be null, how can we handle that.
from tb1 in this.table1 join tb2 in table2 on tb1.Id equals tb2.fkId into temptbl
from aa in temptbl.DefaultIfEmpty()
join tb3 in table3 on tb1.Id equals tb3.StudentId into studentInfo
from pp in studentInfo.DefaultIfEmpty()
join state in tb4 on aa.StateId equals state.StateId into statesTemp
from ss in statesTemp.DefaultIfEmpty()
select new MyModel
{
City = aa == null ? string.Empty : aa.City + ", ",
State = ss == null ? string.Empty : ss.State1,
PostalCode = aa == null ? string.Empty : aa.PostalCode,
studentid = pp.PeopleId
}).ToList()
Upvotes: 3
Views: 300
Reputation: 37299
Problem is that when left joining table tb4
you are accessing aa
's StateId
property. However aa
itself is the result of a left join and thus might be null. Accessing its property will throw the exception.
As you are using C# 5.0 you should:
join state in tb4 on (aa == null ? null : aa.StateId) equals state.StateId
For C# 6.0 and newer you can use the?.
null propagation operator instead.
Upvotes: 2