Entity Framework calling MAX on null on Records

前端 未结 9 1563
傲寒
傲寒 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:46

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

提交回复
热议问题