Get Record ID in Entity Framework after insert Get Record ID in Entity Framework after insert asp.net asp.net

Get Record ID in Entity Framework after insert


Following the call to _dbContext.SaveChanges(), the entity will automatically be updated with its new identity field value.

The following code assumes your Entity Framework entity container name is MyEntities, and your database's Client table has at least the two following fields:

client_id   int identityclient_name varchar(25)

Your code might look something like this:

// Establish DbContextprivate readonly MyEntities _dbContext = new MyEntities();// Create new client table entity and initialize its propertiesvar clientEntity = new Client { client_name="MyCo" };// Add it to the ORM's collection of Client entities_dbContext.Clients.Add(clientEntity);// Save the new entity to the database_dbContext.SaveChanges();// Return the identity field from the existing entity,//   which was updated when the record was saved to the databasereturn clientEntity.client_id;


After you have inserted the entity it should be updated so that the property that maps to the primary key in the database has the new PK value.

Like MyObject.Id will give you the new Id


This is what i'm looking for.

in partial class

protected void clientDataSource_OnInserted(object sender, EntityDataSourceChangedEventArgs e ){    int newPrimaryKey = ((Client)e.Entity).ClientId;    Debug.WriteLine(" Client ID is " + newPrimaryKey);}

and added below line in EntityDataSource in aspx page.

OnInserted="clientDataSource_OnInserted"