【问题标题】:linq to sql left join, need to check for null for right tablelinq to sql left join,需要检查右表是否为空
【发布时间】:2012-06-14 12:05:40
【问题描述】:

我在 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.....errorDefaultIfEmpty() 到底在做什么??

【问题讨论】:

    标签: c# linq linq-to-sql


    【解决方案1】:

    你做的是对的。

    msdn,DefaultIfEmpty 返回:

    一个 IEnumerable 对象,其中包含 如果源为空,则为 TSource 类型;否则,来源。

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

    【讨论】:

    • 谢谢,其实我有很多字段,每个字段都要检查是否为空,我觉得编程有点脏,所以想有没有其他方法可以做到这一点..
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多