Skip to content

Entity Framework – Getting the ID of an Inserted Entity

Last week I was asked by a junior developer how to get the ID of a newly-inserted entity in Entity Framework (Core). He was working on some .NET Core data access code building some CRUD methods, and wanted his Insert() to return the ID auto-generated by the database upon insert.

Entity Framework makes this really easy once your entity classes are setup properly (which can be automated using EF’s scaffolding feature if you’ve already got a database setup).  

Here’s an example of how it’s done:

using (var context = new RapperContext())
	var rapper = new Rapper()
		Name = "Rakim"

	int newRapperId = rapper.RapperId;

Like I said, super simple. All you have to do is add the new entity to the context and call SaveChanges(). EF will automatically call SCOPE_IDENTITY after an insert to retrieve the new ID and populates that entity’s ID field with the value.

More info straight from the horse’s (Microsoft’s) mouth can be found here.

Published inTips & Tricks

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *