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 materialized value is null. Either the result type’s generic parameter or the query must use a nullable type.

try this


int? maxGroupID = db.Users.Max(u => (int?)u.maxGroupID );


Dim maxGroupID As System.Nullable(Of Integer) = db.Users.Max(Function(u) CType(u.fdGroupID, System.Nullable(Of Integer)))