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 can use try/catch and write extenstion:
public static class QueryableExtensions
{
public static TResult? MaxOrDefault(this IQueryable query, Expression> selector) where TResult : struct
{
try
{
return query.Max(selector);
}
catch
{
return null;
}
}
}
And use it as the following:
var version = ctx.Entries
.Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
.MaxOrDefault(e => e.Version);