【问题标题】:LINQ: Set a default value if navigation property is nullLINQ:如果导航属性为空,则设置默认值
【发布时间】:2016-11-26 06:45:31
【问题描述】:

这是我当前的 LINQ 语句:

var results = from l in leads
    select new MyObject
    {
        LeadID = l.LeadID,
        SelectedProposalEngineerID = l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer).FirstOrDefault().ContactID
    };

我遇到的问题是最后一项通常为空。因此,当我尝试将“结果”转换为列表时,我得到了

{“转换为值类型'System.Int32'失败,因为具体化的值为null。结果类型的泛型参数或查询必须使用可为空的类型。”}

我不想将 SelectedProposalEngineerID 设为可为空的 int,因为这会导致下游问题。当它为空时,我如何给它一个值 0?

我已经看到很多关于此的其他线程,但我似乎无法将他们的任何答案用于此案例。

【问题讨论】:

  • 两个澄清 - (1) 你确定异常与 SelectedProposalEngineerID 相关吗? (2)“最后一项”(通常为空)是什么意思?潜在客户、联系人或选定联系人上的 FirstOrDefault()?
  • 好问题。让我在我调查完之后回复你
  • 好的,所以 LeadContact 表中并不总是有 LeadContact.LeadId 等于 Lead.LeadId 的行
  • @Fabio 的回答是对的

标签: c# linq


【解决方案1】:

使用DefaultIfEmpty扩展方法。

var results = from l in leads
    select new MyObject
    {
        LeadID = l.LeadID,
        SelectedProposalEngineerID = 
            l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer)
                          .Select(contact => contact.ContactID)
                          .DefaultIfEmpty(0)
                          .FirstOrDefault()
    };

【讨论】:

    【解决方案2】:
    Nullable<int> ID;
    var results = from l in leads
    select new MyObject
    {
        LeadID = l.LeadID,
        SelectedProposalEngineerID = (ID = l.LeadContacts.Where(contact => contact.LeadContactTypeID == LeadContactType.ProposalEngineer).FirstOrDefault().ContactID).HasValue ? ID.Value : 0;
    };
    

    三元运算符应该可以完成这项工作。将结果赋值给一个变量,如果它不为null,则将该变量转换为int并返回,否则返回0。

    【讨论】:

    • 是的,我试过了。我得到:操作员??不能应用于int和int的类型?
    • 编辑我的答案只是为了正确,@Fabio 的答案是要走的路。
    猜你喜欢
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2017-12-03
    • 2017-12-05
    • 2017-05-15
    相关资源
    最近更新 更多