LINQ查询可空总和 [英] Linq query with nullable sum

查看:145
本文介绍了LINQ查询可空总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 从我Db.Items
选择新VotedItem
{
    ITEMID = i.ItemId,
    点=(从Db.Votes v
              其中,b.ItemId == v.ItemId
              选择v.Points).SUM()
}

我得到这个查询,但如果没有得票数与异常发现失败:

 的空值不能分配给类型System.Int32一个成员是一个非空的值类型。

我认为它的,因为总和返回一个int,而不是一个可空INT,给人总和诠释?作为输入,只给出了同样的错误,很可能导致总和仅workes的整数。

有什么好的解决方法呢?


解决方案

 从我Db.Items
选择新VotedItem
{
    ITEMID = i.ItemId,
    点=(从Db.Votes v
              其中,b.ItemId == v.ItemId
              选择v.Points? 0).SUM()
}

编辑 - 确定这个什么......(再次拍摄,因为我不知道你的模型...):

 从我Db.Items
选择新VotedItem
{
    ITEMID = i.ItemId,
    点=(从Db.Votes v
              其中,b.ItemId == v.ItemId)
              的.sum(V => v.Points)
}

from i in Db.Items
select new VotedItem
{
    ItemId = i.ItemId,
    Points = (from v in Db.Votes
              where b.ItemId == v.ItemId
              select v.Points).Sum()
}

I got this query, however it fails if no votes are found with exception:

The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.

I assume its because sum returns an int and not a nullable int, giving sum a int? as input only give the same error, probably cause sum only workes on ints.

Any good workaround for this?

解决方案

from i in Db.Items
select new VotedItem
{
    ItemId = i.ItemId,
    Points = (from v in Db.Votes
              where b.ItemId == v.ItemId
              select v.Points ?? 0).Sum() 
}

EDIT - ok what about this... (Shooting again since I don't know your model...):

from i in Db.Items
select new VotedItem
{
    ItemId = i.ItemId,
    Points = (from v in Db.Votes
              where b.ItemId == v.ItemId)
              .Sum(v => v.Points) 
}

这篇关于LINQ查询可空总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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