LINQ to Entities query using Sum on child object attribute has a problem.

.net c# entity-framework linq orm

Question

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.

1
7
9/28/2010 3:42:57 PM

Accepted Answer

You should check for it:

HeadCount = s.Reservations != null ? s.Reservations.Sum(r => r.PartySize) : 0,
7
9/28/2010 3:47:14 PM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow