如果使用 Linq 为空,如何获取 table 或 1 的最大 ID?

How can I get the Max id of a table or 1 if empty using Linq?

我通过从 table 中选择最大 ID 并将其递增 1 来手动插入 table 的 ID。如果 table 是空的,最大 returns null 我正在使用下面的代码,但它给出了错误 "The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type"

var t = (from tab1 in db.questions select tab1.QuestionId1).Max();
            if (t!=null)
            {
                 qui = t + 1;
            }

            else
            {
                 qui = 1;
            }

这样的东西行得通吗?

// Assume we want to start with id 1
var maxId = db.Questions
    .Max(q => q.QuestionId1)
    .DefaultIfEmpty(0)
    .Max();

return maxId + 1;

DefaultIfEmpty 将处理空的 table 案例。

数据库通常具有自动递增的 ID 功能。如果您使用的是 Entity Framework,那么它应该默认启用。

您可能正在寻找类似这样的东西,使用 LINQ 的扩展方法语法:

var maxID = db.Questions.Any() 
            ? db.Questions.Max(q => QuestionId1) + 1
            : 1

如果数据库中有Questions则取最高的QuestionId1加1,否则return1.

绝对不是获取 "new ids" 的首选方法(最好让数据库生成它们),但它是这样的:

var maxId = ((from tab1 in db.questions select (int?)tab1.QuestionId1).Max() ?? 0) + 1;

或等同物,但 IMO 更易于阅读:

var maxId = (db.questions.Select(x => (int?)x.QuestionId1).Max() ?? 0) + 1

您最初的问题是您使用 IEnumerable<int> 参数调用 Max(),这不允许它 return 一个空值(它抛出异常),因为return 值是 intint 不能是 null

我正在将 Select() 编辑的可枚举 return 转换为 Nullable<int>(或简称 int?)类型的可枚举,因此 Max() returns 一个 int? 允许它 return null 如果可枚举为空(因为没有选择行时的情况),而不是抛出异常。