【问题标题】:LINQ left join with nullable values带有可为空值的 LINQ 左连接
【发布时间】:2015-08-17 07:52:37
【问题描述】:
from t in Tasks
join user in UserInfo on t.Publisher equals user.Account into temp
from userinfo in temp.DefaultIfEmpty()
select new
{
    t.Title,
    IsCertificated = userinfo.IsCertificated
}

一些代码喜欢。 IsCertificated 为 boolean 类型,当 userinfo 为 null 时,该查询无效。

不为 System.Boolean 分配 Null 值类型

我知道它可以修改:

 select new
    {
        t.Title,
        IsCertificated =userinfo == null?false: userinfo.IsCertificated
    }

但是,我的用户信息有太多非空属性。我该如何处理它?

【问题讨论】:

  • 究竟是什么问题,看来您已经找到解决问题的方法了?
  • @Magnus 谢谢。我的问题是:我的 userinfo 表有太多属性,我认为为每个属性编码 userinfo == null?XX: userinfo.XXX 是一种糟糕的方式。有什么好的方法吗?
  • @yubaolee 创建一个“模型”类...然后您将使用“选择新的 MyUserTaskModel()”...然后在属性设置方法中进行空检查或确实在构造函数等......对象/类映射很无聊......或者使用更自动化的东西,例如 AutoMapper github.com/AutoMapper/AutoMapper

标签: c# linq entity-framework


【解决方案1】:

您可以将条件运算符从对象创建中提取出来。

from t in Tasks
join user in UserInfo on t.Publisher equals user.Account into temp
from userinfo in temp.DefaultIfEmpty()
select userinfo != null
    ? new
        {
            t.Title,
            IsCertificated = userinfo.IsCertificated
        }
    : new
        {
            t.Title,
            IsCertificated = false
        }

【讨论】:

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