int? max = (from t in context.Test select (int?)t.ID).Max(); int m = 0; if (!max.HasValue) { m = 1; } else m = (int)max + 1;