Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ??

like image 680
Meson Avatar asked Jun 14 '12 12:06

Meson


1 Answers

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.

like image 135
Alex Peck Avatar answered Nov 13 '22 20:11

Alex Peck