如何在 ASP.NET Core Web API 中使用 LINQ 仅从数据库获取最新的 id?

Dre*_* OC 1 c# linq asp.net-mvc asp.net-web-api asp.net-core

Id | StName | Subject  | 
 1 |  Tom   |  Math    |
 2 |  Jerry |  Science |
Run Code Online (Sandbox Code Playgroud)

我是 LINQ 新手,我试图使用 LINQ 从数据库中仅获取IdJerry StName 但我做不到。

Id | StName | Subject  | 
 1 |  Tom   |  Math    |
 2 |  Jerry |  Science |
Run Code Online (Sandbox Code Playgroud)

但我得到了所有的数据。我想获取最新记录的id(仅id)。

gun*_*171 5

现在您将获得数据库表中所有记录的列表。当按 Id降序排列时,您只需要第一个

[HttpGet]
public int GetStudentId()
{
    var latestStudentRecord = _context.StudentModel
        .OrderByDescending(a => a.Id)
        .First();

    // return only the Id property of the latest record
    return latestStudentRecord.Id;
}
Run Code Online (Sandbox Code Playgroud)

请注意,只有当您的 Id 是连续的时,这才有效,并且保证“最新”记录始终具有最高的 Id 值。

稍后,如果您的表没有记录,您可能需要交换First()到。FirstOrDefault()

方法签名已更改为仅返回 int 而不是整个列表。