Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with LINQ to Entities query using Sum on child object property

Given this query:

from s in services
select new
{
    s.Id,
    s.DateTime,
    Class = s.Class.Name,
    s.Location,
    s.Price,
    HeadCount = s.Reservations.Sum(r => r.PartySize), // problem here. r.PartySize is int
    s.MaxSeats
}

If the service doesn't have any reservations, this exception is thrown:

System.InvalidOperationException: The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

I get it, but how should I deal with it? My intention is if there are no reservations, then HeadCount be assigned 0.

like image 953
Ronnie Overby Avatar asked Sep 28 '10 15:09

Ronnie Overby


4 Answers

There's an even simpler solution:

from s in services
select new
{
    s.Id,
    s.DateTime,
    Class = s.Class.Name,
    s.Location,
    s.Price,
    HeadCount = (int?)s.Reservations.Sum(r => r.PartySize), 
    s.MaxSeats
}

Note the cast. This may also produce simpler SQL than @Ahmad's suggestion.

Essentially, you're just helping out type inference.

like image 100
Craig Stuntz Avatar answered Nov 10 '22 02:11

Craig Stuntz


You should check for it:

HeadCount = s.Reservations != null ? s.Reservations.Sum(r => r.PartySize) : 0,
like image 37
Ahmad Mageed Avatar answered Nov 10 '22 01:11

Ahmad Mageed


This should resolve your problem: Try to cost the int to int?

from s in services
select new
{
    s.Id,
    s.DateTime,
    Class = s.Class.Name,
    s.Location,
    s.Price,
    HeadCount = s.Reservations.Sum(r => (int?) r.PartySize),
    s.MaxSeats
};
HeadCount = HeadCount ?? 0;
like image 2
amiry jd Avatar answered Nov 10 '22 00:11

amiry jd


A simple ternary operator should fix the problem nicely...

something like this:

HeadCount = (s.Reservations != null && s.Reservations.Any()) ? s.Reservations.Sum(r => r.PartySize) : 0;

This will handle for both null and empty situations

like image 1
Justin Williams Avatar answered Nov 10 '22 00:11

Justin Williams