6

我在 linq to 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 ?
}

查询正确地产生了答案,但如果我不检查这几个字段是否为空,它就会抛出object reference not set.....error。这到底是DefaultIfEmpty()做什么的?

4

2 回答 2

3

你所做的是正确的。

msdn, DefaultIfEmpty 返回:

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

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

于 2012-06-14T12:26:50.580 回答
0

在这种情况下,DefaultIfEmpty 在评估的左侧为您提供了一个空对象。因此,尝试调用 ujoinx.employeeSal 将返回未设置对象引用,因为 ujoinx 为空。

于 2012-06-14T12:22:10.243 回答