asp.netentity-framework-4.1detailsview

Get Record ID in Entity Framework after insert


I'm developing an ASP.net application using Entity Framework. I'm using DetailsView to insert data into database. There is a table as Client and its primary key is client_id. client_id is auto generated by database. I need to get auto generated client_id after inserting a record into Client table and assign it to a hidden field for future use.

I searched about this and I found lot of solutions. But I don't know how to use them since I'm new to asp.net. I found that Entity Framework automatically populates business objects with the db-generated values after call SaveChanges(). My question is where should I call this in my partial class ? What is the event ?

I'm using DetailsView with EntityDataSource and binding EntityDataSource directly with Entity Model, so I'm not creating objects to insert data.


Solution

  • 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"