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

.net c# entity-framework linq orm

Question

This question:

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
}

This exception is issued if the service has no reservations:

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 what should I do about it? If there are no bookings, I want HeadCount to be set to 0.

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

Accepted Answer

You ought to look for it:

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

Popular Answer

There is an even easier remedy:

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
}

Observe the cast. In comparison to @Ahmad's idea, this could also result in easier SQL.

In essence, all you're doing is aiding 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