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
You could write a simple extension method like this, it returns the default value of type T if no records exist and is then apply Max to that or the query if records exist.
public static T MaxOrEmpty(this IQueryable query)
{
return query.DefaultIfEmpty().Max();
}
and you could use it like this
maxId = context.Competition.Select(x=>x.CompetitionId).MaxOrEmpty();