Entity Framework calling MAX on null on Records

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

    I couldnt take no for an answer :) I have tested the below and it works, I havent checked the SQL generated yet so be careful, I will update this once I have tested more.

    var test = ctx.Entries
        .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
        .MaxOrDefault(x => x.Version);
    
    public static TResult? MaxOrDefault(this IEnumerable source, Func selector)
        where TResult : struct
    {
        return source
            .Select(selector)
            .Cast()
            .Max();
    }
    

提交回复
热议问题