Entity Framework calling MAX on null on Records

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

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

提交回复
热议问题