简体   繁体   中英

Get Id's of recently inserted rows in Entity Framework

I'm bulk inserting rows into a table (which has a identity column which auto increments every time a new row is inserted) based on the following post

https://stackoverflow.com/a/5942176/3861992

After all rows are inserted, how do I get the list of ids of the rows that are recently inserted?

Thanks

EntityFrameWork(EF) after insert entity and SaveChanges() . it sets the value of Id.
Suppose that the entity you want to enter into database is as follows:

 public class EntityToInsert
  {
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
  }

And you want to insert a list of entity:

 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();

I hope this helps.

When all rows are really inserted in the database(after calling SaveChanges() in Entity Framework), the real IDs of these rows are populated.

So after SaveChanges() you will have IDs there in inserted objects without doing any query.

Try this: dbcontext.Entry( [object] ).GetDatabaseValues();

This is for a single row. If my internet connection at the moment wasn't so slow I'd look up the documentation to see if it's easy to get multiple rows. At the very least you can iterate through your list of database objects and get each entries values. That however may not be the fastest solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM