How to find an identity of the last inserted row in Entity Framework?

前端 未结 2 462
你的背包
你的背包 2020-12-13 09:04

I am inserting data in multiple tables. I need to know the last inserted (auto-incremented) ID in the table. I need to use it as a Foriegn Key in some other table.

I

相关标签:
2条回答
  • 2020-12-13 09:36

    Entity Framework will automatically load the last inserted id to populate the primary key column of the inserted entity:

    var customer = new Customer { Name = "Steven" };
    
    context.AddObject(customer);
    
    context.SaveChanges();
    
    var id = customer.Id;
    

    Note that the Id property only gets populated after calling SaveChanges() in case the StoreGeneratedPattern attribute is set to "Identity" or "Computed" for the auto-incremented ID column in the Storage part of the model.

    0 讨论(0)
  • 2020-12-13 09:37

    Anyhow if you need the the id for some any other purpose ... calling EF Insert Method for some entity automatically returns the currently inserted row id ...

    var rowId=db.Insert(Entity); 
    
    0 讨论(0)
提交回复
热议问题