Validating nulls with linq

1

I have the following query in linq

using (var context = new BusinessContext())
        {
            var result = (from m in context.MovimientoCajas
                where DbFunctions.TruncateTime(m.Fecha) == DbFunctions.TruncateTime(fecha)
                      && m.PuntoEmisionId == puntoEmision && m.TipoMovimiento == MovimientoCajaType.Ingreso
                select m.Ingreso).Sum();
            return result;
        }

The query works fine but when there is no data on that date because nothing has been entered it still gives me the following error.

  

The conversion to value of type 'System.Decimal' failed because the value   materialized is null. The generic parameter of the result type or   the query must use a type that may contain nulls.

I understand the problem, my question is whether it could validate in the same line of select select m.Ingreso).Sum(); or necessarily I have to do select new and cast it in a class and map it to a property of decimal type. What is the most advisable?

    
asked by Pedro Ávila 19.12.2018 в 14:37
source

2 answers

1

If you detect that the problem is due to the lack of records you can always validate it

var query = from m in context.MovimientoCajas
                where DbFunctions.TruncateTime(m.Fecha) == DbFunctions.TruncateTime(fecha)
                      && m.PuntoEmisionId == puntoEmision && m.TipoMovimiento == MovimientoCajaType.Ingreso
                select m.Ingreso;

if(query.Count > 0){
    return query.Sum();
}

return 0;

or also use a line

return query.Count == 0 ? 0 : query.Sum();

you should also validate that the property Ingreso does not allow null, since not having a data would cause problems

    
answered by 19.12.2018 / 14:51
source
0

You can cast Nullable the property m.Income and then with the operator ?? I say that if it is null, return 0.

var result = (from m in context.MovimientoCajas
                      where DbFunctions.TruncateTime(m.Fecha) ==DbFunctions.TruncateTime(fecha)
                            && m.PuntoEmisionId == puntoEmision && m.TipoMovimiento == MovimientoCajaType.Ingreso
                      select m.Ingreso as decimal? ?? 0).Sum();
    
answered by 19.12.2018 в 14:59