linq to sql left join,需要为右表检查null

Mes*_*son 6 c# linq linq-to-sql

我正在左边加入linq到sql,所以我的问题是在选择正确的表字段时,我正在检查每个字段,而连接对象是否为空,这是正确的方法吗?或者还有其他方法吗?我的查询就像

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 ?
}
Run Code Online (Sandbox Code Playgroud)

查询得到了正确的答案,但如果我不检查那些几个字段为null抛出它object reference not set.....error.这到底是DefaultIfEmpty()什么?

Ale*_*eck 3

你所做的是正确的。

msdn中,DefaultIfEmpty 返回:

一个 IEnumerable<T> 对象,如果 source 为空,则包含 TSource 类型的默认值;否则,来源。

换句话说,当集合为空时,它将返回 T 的默认值。引用类型的默认值为 null - 这就是为什么在选择 DeptName 时必须检查 null 的原因。