获取实体框架中最近插入的行的 ID

use*_*992 1 c# sql entity-framework

我根据以下帖子将行批量插入到表中(它有一个标识列,每次插入新行时都会自动递增)

/sf/answers/415952351/

插入所有行后,如何获取最近插入的行的 id 列表?

谢谢

Sae*_*jad 6

EntityFrameWork(EF)在插入实体和之后SaveChanges()它设置 Id 的值。
假设您要输入数据库的实体如下:

 public class EntityToInsert
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
  }
Run Code Online (Sandbox Code Playgroud)

并且你想插入一个实体列表:

 var list = new List<EntityToInsert>()
        {
            new EntityToInsert() {Name = "A", Age = 15},
            new EntityToInsert() {Name = "B", Age = 25},
            new EntityToInsert() {Name = "C", Age = 35}
        };
        foreach (var item in list)
        {
            context.Set<EntityToInsert>().Add(item);
        }
        context.SaveChanges();
       // get the list of ids of the rows that are recently inserted
        var listOfIds=list.Select(x => x.Id).ToList();
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。