LINQ Sum()中的IsNull [英] IsNull in LINQ Sum()

查看:137
本文介绍了LINQ Sum()中的IsNull的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在LINQ中遇到IsNull问题:

I have problem with IsNull in LINQ :

db.WarehouseInputsDetails
    .Select(p => new WarehouseInputDetailsViewModel
    {
        Id = p.Id
        RemainingQuantity = p.Quantity - p.LoadingsDetails.Sum(n => n.Quantity)
    }).AsQueryable();

p.LoadingsDetails.Sum(n => n.Quantity)可能性NULL.我想要这样的结果:

p.LoadingsDetails.Sum(n => n.Quantity) possibility NULL. I want to have result like this :

select Id, IsNull(Sum(Quantity),0) as Quantity from LoadingsDetails

我尝试过类似的事情:

db.WarehouseInputsDetails
    .Select(p => new WarehouseInputDetailsViewModel
    {
        Id = p.Id
        RemainingQuantity = p.LoadingDetails.First() == null ? p.Quantity : p.Quantity - p.LoadingsDetails.Sum(n => n.Quantity)
    }).AsQueryable();

返回错误:

System.NotSupportedException:方法"First"只能用作 最终查询操作.考虑在其中使用方法"FirstOrDefault" 代替这个实例.

System.NotSupportedException: The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead.

我尝试过这样的事情:

db.WarehouseInputsDetails
    .Select(p => new WarehouseInputDetailsViewModel
    {
        Id = p.Id
        RemainingQuantity = (p.LoadingsDetails.Sum(n => n.Quantity) == DBNull.Value) ? p.Quantity : p.Quantity - p.LoadingsDetails.Sum(n => n.Quantity)
    }).AsQueryable();

OR

db.WarehouseInputsDetails
    .Select(p => new WarehouseInputDetailsViewModel
    {
        Id = p.Id
        RemainingQuantity = p.LoadingsDetails.First().Quantity == DBNull.Value ? p.Quantity : p.Quantity - p.LoadingsDetails.Sum(n => n.Quantity)
    }).AsQueryable();

返回错误:

运算符'=='不能应用于类型'decimal'和'DBNull'的操作数

Operator '==' cannot be applied to operands of type 'decimal' and 'DBNull'

推荐答案

您可以在此处使用Any(),它将检查LoadingDetails是否存在任何行,如果是,则将Quantity求和为LoadingDetails:

You can use Any() here which will check if there is any row for LoadingDetails, if yes then Sum the Quantity for LoadingDetails:

RemainingQuantity = p.LoadingDetails.Any()  ? 
                p.Quantity - p.LoadingsDetails.Sum(n => n.Quantity) : 
                p.Quantity 

这篇关于LINQ Sum()中的IsNull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆