Linq to sql left join, you need to check the null value for the right table

i doin 'left join in linq to sql, so my question is choosing the right fields of the table, I check each field because the merged object is null or not, is this correct? or is there any other way to do this? my request 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 request, as a result, received the answer correctly, but if I do not check these few fields for null, it will throw an object reference not set.....error . Here is what is DefaultIfEmpty() to do exactly ??

+6
source share
2 answers

What you have done is right.

From msdn , DefaultIfEmpty returns:

IEnumerable <T> object that contains the default value for the TSource type if the source is empty; otherwise a 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 should check for null when choosing DeptName.

+3
source

DefaultIfEmpty in this case gives you the null object on the left side of evaulation. Thus, an attempt to call ujoinx.employeeSal will return an object reference if not, because ujoinx is null.

0
source

Source: https://habr.com/ru/post/918090/


All Articles