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

Posted

技术标签:

【中文标题】如何在 ASP.NET Core Web API 中使用 LINQ 仅从数据库中获取最新的 id?【英文标题】:How to get latest id only from database using LINQ in ASP.NET Core Web API? 【发布时间】:2020-12-13 03:30:46 【问题描述】:
Id | StName | Subject  | 
 1 |  Tom   |  Math    |
 2 |  Jerry |  Science |

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

[HttpGet]
public IEnumerable<StudentModel> GetStudentId()

    var id = _context.StudentModel.OrderBy(a => a.Id).ToList();
    return(id);

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

【问题讨论】:

我要获取新记录的id(只有id) 是的,它只会返回一个Id。看看,让我知道它是否按预期工作。 【参考方案1】:

现在,您正在获取数据库表中所有 条记录的列表。您只需要 第一个按 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;

请注意,这仅在您的 Id 是连续的情况下才有效,并且保证“最新”记录将始终具有最高的 Id 值。

稍后,如果您的表没有记录,您可能希望将First() 交换为FirstOrDefault()

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

【讨论】:

【参考方案2】:

你可以试试下面的代码。

[HttpGet]
public int GetStudentId()

    var id = _context.StudentModel.OrderByDescending(a => a.Id).FirstOrDefault();
     return id.Id;

你也可以像下面这样写:

[HttpGet]
public int GetStudentId()

     var id = _context.StudentModel.Max(a => a.Id).FirstOrDefault();
     return id.Id;

注意:你要做的是,需要过滤数据库实体的最大值或顶部条目,然后返回它。我也这样做了。

【讨论】:

public IEnumerable GetStudentId() 当我使用它时,我得到返回错误(id.Id),错误:无法将类型 int 隐式转换为 System.Collections.Generic ..... ...... 更新了答案,虽然你不需要返回 IEnumerable&lt;StudentModel&gt; 你想要一个 id 对吗? 是的,我需要新记录的 id(只有单个 id),当我使用 public int GetStudentId() var id = _context.StudentModel.OrderByDescending(a => a.Id) 时你的代码很好.FirstOrDefault();返回 id.Id; 是的!你的代码也是一样的。那么如果我只想返回字符串数据而不是 Id 怎么办? (StName=Tom)【参考方案3】:

更改方法以返回与您的 Id 相同的类型,然后仅获取集合的第一项并返回其属性 Id。

应该是这样的。

public int GetStudentId()

    var student = _context.StudentModel.OrderBy(a => a.Id).FirstOrDefault();
    return student.Id;

【讨论】:

以上是关于如何在 ASP.NET Core Web API 中使用 LINQ 仅从数据库中获取最新的 id?的主要内容,如果未能解决你的问题,请参考以下文章