Niels Brinch
Niels Brinch

Reputation: 3612

LINQ with Entity Framework, getting calculated sum

I have the following data:

enter image description here

Number can be NULL

I am writing a LINQ statement to get the following number as a result:

Needed result: 290

My LINQ statement currently looks like this:

(from b in data
where b.Number.HasValue
select new
{
    Number = b.Number.Value,
    b.Factor
}).Sum(o => o.Number * (o.Factor / 100));

I get the following error:

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

Upvotes: 2

Views: 5424

Answers (1)

Niels Brinch
Niels Brinch

Reputation: 3612

This can be fixed by casting the contents of the Sum like this:

(from b in data
where b.Number.HasValue
select new
{
    Number = b.Number.Value,
    b.Factor
}).Sum(o => (decimal?)(o.Number * ((decimal)o.Factor / 100))) ?? 0;

(note: I found the answer while writing the question and thought I might as well formulate an answer and publish it for anyone else to find)

Upvotes: 5

Related Questions