Use Entity Framework to get the identity of the inserted entity
Entity Framework provides a convenient way to insert entities into the database. However, getting the database-assigned ID of the inserted entity can be a challenge. This article addresses this issue by exploring two approaches.
Method 1: Use assigned entity ID
This article starts with a solution on the Entity Framework website that involves getting the assigned ID from the entity object itself. Although this method returns the entity's internal ID, it may not be consistent with the database table's ID if the record is deleted.
Method 2: Retrieve database identifier
A more reliable method is to retrieve the database generated ID. This can be achieved by simply adding the entity to the ObjectSet and calling SaveChanges on the relevant ObjectContext. Entity Framework automatically sets the entity's Id property with the database-assigned identity:
<code>using (var context = new MyContext()) { context.MyEntities.Add(myNewObject); context.SaveChanges(); int id = myNewObject.Id; // 数据库标识可用 }</code>
Entity Framework executes a SELECT SCOPE_IDENTITY() query after each INSERT to retrieve the generated ID, ensuring accurate ID retrieval.
The above is the detailed content of How to Retrieve the Database-Generated ID After Inserting an Entity with Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!