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
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;
}