Sumasync return zero

Asked

Viewed 60 times

2

I have an appointment in LINQ where do I use the SumAsync, however when my entity is empty I have the exception:

The cast to value type 'System.Decimal' failed because the materialized value is null. Either the result type’s Generic Parameter or the query must use a nullable type.

The appointment I’m trying to make is this:

var valor = await db.Exemplos.SumAsync(a => a.Valor);

How can I get around that and do the SumAsync return 0 if my entity has no data yet?

1 answer

4


What happens is that the Sum is being called in a IQueryable and this means that the implementation of this method is delegated to the preview of Queryable, ie - as you might imagine, who executes the Sum, actually, it’s SQL Server. You can check this behavior on source code on referencesource.

Error bursts precisely because SQL Server returns NULL when trying to execute a SUM in an "empty collection".

You can cast the a.Valor for decimal? (nullable decimal) and use the operator coalesce in the final result.

var valor = await db.Exemplos.SumAsync(a => (decimal?) a.Valor) ?? 0;
  • But it will be some kind of limitation of the Sumasync function that it no longer treats this kind of situation?

  • @Pablotondolodevargas I edited the answer to contemplate it

  • But if I do db.Exemplos.Sum(a => a.Valor), I’d have to cast it like Sumasync?

  • @Pablotondolodevargas For sure. The method should be asynchronous or not make a difference in behavior.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.