简体   繁体   中英

Max throws InvalidOperationException

I Have this query

decimal? query = context.History
   .Where(x => x.ItemId == Id
       && x.OtherFilter == IdOtherFilter
       && x.Fecha < Fecha)
   .Select(x => x.Secuencia)
   .Max();

I need to perform this query into Linq:

select max(Secuencia)
    from History
    where ItemId= 1406 
        and OtherFilter= 3
        and Fecha < '20150922'
        group by OtherFilter

I need to get the max Secuencia from a table that match with criteria, it works fine when criteria returns data, but when no data match with criteria, Max() can't materialize throwing an InvalidOperationException ,

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. 

how to avoid that ?

There is another Linq that I can use ?

are those sentences equivalent? if not What is wrong in my linq?

Assuming that the type of the Secuencia property is decimal and not decimal? , you should try adding a cast to decimal? so that Max will return null in the case that there are no values.

decimal? query = context.History
   .Where(x => x.ItemId == Id
       && x.OtherFilter == IdOtherFilter
       && x.Fecha < Fecha)
   .Select(x => (decimal?) x.Secuencia)
   .Max();

or

decimal? query = context.History
   .Where(x => x.ItemId == Id
       && x.OtherFilter == IdOtherFilter
       && x.Fecha < Fecha)
   .Select(x => x.Secuencia)
   .Cast<decimal?>()
   .Max();

Make following modification to make it work, add DefaultIfEmpty() before Max() call, this will take care of empty list , also you may specify custom default value like 0.0 , here it would be null , since the type selected is a nullable value type , check DefaultIfEmpty

decimal? query = context.History
   .Where(x => x.ItemId == Id
       && x.OtherFilter == IdOtherFilter
       && x.Fecha < Fecha)
   .Select(x => x.Secuencia)
   .DefaultIfEmpty()
   .Max();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM