Get Record ID in Entity Framework after insert

前端 未结 4 1398
北荒
北荒 2021-02-07 02:34

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

4条回答
  •  逝去的感伤
    2021-02-07 03:10

    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 identity
    client_name varchar(25)
    

    Your code might look something like this:

    // Establish DbContext
    private readonly MyEntities _dbContext = new MyEntities();
    
    // Create new client table entity and initialize its properties
    var 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 database
    return clientEntity.client_id;
    

提交回复
热议问题