Linq query with nullable sum

前端 未结 14 1882
粉色の甜心
粉色の甜心 2020-11-29 06:23
from i in Db.Items
select new VotedItem
{
    ItemId = i.ItemId,
    Points = (from v in Db.Votes
              where b.ItemId == v.ItemId
              select v.Poi         


        
相关标签:
14条回答
  • 2020-11-29 06:54

    Just to add another method into the mix :)

    Where(q=> q.ItemId == b.ItemId && b.Points.HasValue).Sum(q=>q.Points.Value)
    

    I had a similar scenario but I wasn't comparing an additional field when summing...

    Where(q => q.FinalValue.HasValue).Sum(q=>q.FinalValue.Value);
    
    0 讨论(0)
  • 2020-11-29 06:56

    You want to use the nullable form of Sum, so try casting your value to a nullable:

    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(r => (decimal?) r.Points)
    }
    

    Your issue is discussed here in more detail:

    http://weblogs.asp.net/zeeshanhirani/archive/2008/07/15/applying-aggregates-to-empty-collections-causes-exception-in-linq-to-sql.aspx

    0 讨论(0)
  • 2020-11-29 06:57

    I had a similar issue and came up with the solution of getting whatever I was trying to get out of the database, do a count on those and then only if I had anything returned do a sum. Wasn't able to get the cast working for some reason so posting this if anyone else had similar issues.

    e.g.

    Votes = (from v in Db.Votes
              where b.ItemId = v.ItemId
              select v)
    

    And then check to see if you've got any results so that you don't get null returned.

    If (Votes.Count > 0) Then
        Points = Votes.Sum(Function(v) v.Points)
    End If
    
    0 讨论(0)
  • 2020-11-29 06:57

    Thought I would throw another solution out there. I had a similar issue and this is how I ended up solving it:

    Where(a => a.ItemId == b.ItemId && !b.IsPointsNull()).Sum(b => b.Points)
    
    0 讨论(0)
  • 2020-11-29 06:59

    Assuming "v.Points" is a decimal just use the following:

    from i in Db.Items
    select new VotedItem
    {
        ItemId = i.ItemId,
        Points = (from v in Db.Votes
                  where b.ItemId == v.ItemId
                  select (decimal?) v.Points).Sum() ?? 0
    }
    
    0 讨论(0)
  • 2020-11-29 06:59

    Try to check this out:

    var count = db.Cart.Where(c => c.UserName == "Name").Sum(c => (int?)c.Count) ?? 0;
    

    So, the root of the problem is that SQL query like this:

    SELECT SUM([Votes].[Value])
    FROM [dbo].[Votes] AS [Votes]
    WHERE 1 = [Votes].[UserId] 
    

    returns NULL

    0 讨论(0)
提交回复
热议问题