Home > Backend Development > C++ > How Do I Retrieve a Database-Generated ID After Inserting an Entity in Entity Framework?

How Do I Retrieve a Database-Generated ID After Inserting an Entity in Entity Framework?

Mary-Kate Olsen
Release: 2025-01-21 11:11:09
Original
607 people have browsed it

How Do I Retrieve a Database-Generated ID After Inserting an Entity in Entity Framework?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template