🔥 Articles, eBooks, Jobs, Columnist, Forum, Podcasts, Courses 🎓

Insert and Get the result Id inserted using CSharp and Entity Framework | ecode10.com


Insert and Get the result Id inserted using CSharp and Entity Framework

In practice

When performing an insert operation in C# using Entity Framework, if your entity's primary key property is configured as an identity column in the database (e.g., auto-incrementing integer), Entity Framework automatically populates this ID property on the entity object after SaveChanges() or SaveChangesAsync() is called.

Here's how to retrieve the ID:

Add the entity to the DbContext.

var newEntity = new YourEntity { Name = "Example" };
_dbContext.YourEntities.Add(newEntity);

Code 1 - Save changes to the database.

await _dbContext.SaveChangesAsync(); // Or _dbContext.SaveChanges();

Code 2 - Access the ID from the entity object:

var insertedId = newEntity.Id; // Assuming 'Id' is the primary key property

Code 3 - Get the ID

Explanation:

Entity Framework tracks the state of your entities. When SaveChanges() is called, EF sends the insert command to the database. If the database generates the primary key, EF then retrieves this generated ID and updates the corresponding property on the entity object that is being tracked in the DbContext. Therefore, you can access the ID directly from the entity instance after the save operation.

I hope you enjoyed the code and you can talk to me any time using my website www.mauriciojunior.net.





Related articles




Top