Entity Framework calling MAX on null on Records

前端 未结 9 1572
傲寒
傲寒 2020-12-08 09:29

When calling Max() on an IQueryable and there are zero records I get the following exception.

The cast to value type \'Int32\' failed because the materialize

9条回答
  •  臣服心动
    2020-12-08 09:58

    I want to suggest a merge from the existing answers:

    @divega answer works great and the sql output is fine but because of 'don't repeat yourself' an extension will be a better way like @Code Uniquely showed. But this solution can output more complex sql as you needed. But you can use the following extension to bring both together:

     public static int MaxOrZero(this IQueryable source, 
     Expression> selector)
            {
                var converted = Expression.Convert(selector.Body, typeof(int?));
                var typed = Expression.Lambda>(converted, selector.Parameters);
    
                return source.Max(typed) ?? 0;
            }
    

提交回复
热议问题