SumAsync return zero

2

I have a query in LINQ where I use 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 query I'm trying to do is as follows

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

How can I work around this and make SumAsync return 0 if my entity does not have data yet?

    
asked by anonymous 08.01.2018 / 14:53

1 answer

4

What happens is that Sum is being called in IQueryable and this causes the execution of this method to be delegated to the provider of Queryable , ie - as you you should already know, who runs Sum , in fact, is SQL Server. You can see this behavior in the source code in referencesource a>.

The error pops up just because SQL Server returns NULL when trying to execute a SUM on an "empty collection".

You can cast the cast from a.Valor to decimal? ( coalesce in the final result.

var valor = await db.Exemplos.SumAsync(a => (decimal?) a.Valor) ?? 0;
    
08.01.2018 / 14:58