Retrieve database generated ID in Entity Framework
When inserting objects into a database using Entity Framework (EF), it is often necessary to obtain the database-generated ID of the newly inserted entity. EF provides a convenient way to achieve this:
<code class="language-csharp">using (var context = new MyContext()) { context.MyEntities.Add(myNewObject); context.SaveChanges(); int id = myNewObject.Id; // ID 现在可用 }</code>
When using automatically generated IDs (such as IDENTITY in MS SQL), EF automatically executes a SELECT SCOPE_IDENTITY() query after each INSERT statement. This ensures that the ID property of the inserted object is correctly populated with the database assigned value.
However, it is important to note that this method only works with database-generated IDs. If you use a custom generated ID (such as a GUID), you need to manually set the ID property before adding the object to the context:
<code class="language-csharp">myNewObject.Id = Guid.NewGuid(); context.MyEntities.Add(myNewObject); context.SaveChanges();</code>
The above is the detailed content of How Do I Retrieve a Database-Generated ID After Inserting an Entity in Entity Framework?. For more information, please follow other related articles on the PHP Chinese website!