linq to sql left join, need to check for null for right table

c#, linq, linq-to-sql

Solution

What you have done is correct.

From msdn, DefaultIfEmpty returns:

An IEnumerable<T> object that contains the default value for the TSource type if source is empty; otherwise, source.

In other words, when the collection is empty, it will return the default value for T. The default value for reference types is null - this is why you must check for null when you select DeptName.

Problem

i'm doin' left join in linq to sql, so my question is while selecting the right table fields, i'm checking each field wheather the joined object is null or not, is this the correct way ? or is there any other way to do it ? my query is like ``` from u in user join x in employeee on u.id equals x.userId into ux from ujoinx in ux.DefaultIfEmpty() join y in department on x.id equals y.employeeId into xy from xjoiny in xy.DefaultIfEmpty() select new { EmployeeSal = ujoinx!=null?ujoinx.employeeSal:0, // see checkig for null EmployeeTax = ujoinx!=null?ujoinx.employeeTax:0, // in this 3 lines UserName = u.username, DeptName = xjoiny!=null?xjoiny.name:"" //is this a correct way ? } ``` The query resulting the answer properly but if i dont check those few fields for null its throwing `object reference not set.....error`. Here what is that `DefaultIfEmpty()` doin exactly ??

Original source