【问题标题】:How to check the null of an embedded linq to entities statement如何检查嵌入式 linq to entity 语句的空值
【发布时间】:2010-12-15 11:55:31
【问题描述】:

使用 linq 连接到数据库的实体,该数据库中有表,其中包含与工作具有多对多关系的付款。这是通过分配表实现的。我想要一个包含所有工作的列表框,其中包含一个名为到期价格的列,该列包含该工作的所有付款分配并将其从工作价格中扣除。但是,使用下面的 linq to entity 语句。问题是,如果作业没有分配,则返回 null,因此到期付款为空。我真正想要的是,如果没有分配,到期付款就是工作价格,但是,我想不出办法解决这个问题。请在我最终发疯之前提供帮助:-(

           var jobs = from j in data.jobs
                   where j.property.customer.id == customerid
                   && j.completed != null
                   select new
                   {
                       j.id,
                       j.price,
                       dueprice = j.price - ( from a in data.allocs
                                              where a.job.id == j.id
                                              select a.amount ).Sum(),

                       lineone = j.property.lineone,
                       postcode = j.property.postcode,
                       jobtype = j.jobtype.name,
                       j.completed
                   };

【问题讨论】:

    标签: c# .net asp.net linq linq-to-entities


    【解决方案1】:

    您还可以使用Null Coalescing 运算符来简化代码,如下所示:

             dueprice = j.price - (( from a in data.allocs 
                                              where a.job.id == j.id 
                                              select a.amount ).Sum() ?? 0)
    

    该运算符返回第一个不为空的值,所以myNum ?? 0如果不为空则返回myNum,如果为空则返回0。

    【讨论】:

    • 太好了,我认为必须有一种更简单的方法,而且这种方法有效。谢谢
    【解决方案2】:
    select a.amount ).Concat(/* array with one zero element */).Sum()
    

    【讨论】:

      【解决方案3】:

      实际上我自己找到了答案,我会尝试 oleg's 以及它似乎更精确但我想这样做

                              dueprice = j.price - (( from a in data.allocs
                                                    where a.job.id == j.id
                                                    select a.amount ).Sum())==null ? j.price:
                                           //sets the due price to the normal sum if it has allocs
                                           j.price - ( from a in data.allocs
                                                    where a.job.id == j.id
                                                    select a.amount ).Sum(),
      

      但是我喜欢只添加更多代码行而不是我的几个(加上它是重复的代码)的想法,我会尝试这个并让大家知道。感谢您的回复。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 2013-10-11
        相关资源
        最近更新 更多