Home » C# » How to return the ID from an EF entity after Add / Create

How to return the ID from an EF entity after Add / Create

By Emily

If you’ve been working with Entity Framework you may well be wondering how you get the id of a newly created Entity record. I’ve been working on a .Net Core API lately, which uses Entity Framework (EF Core), and after I create a new record in the database, I wanted to be able to then get and show the the new record. To do so, I would need to get the id of the EF Core added entity, and I wasn’t sure how to do that. This post explains how to do this, with code examples.

Some background context

In my case, I was building a fairly standard API where each Entity would need a Create, Read, Update, and Delete method. I’d decided to use the Repository pattern along with Entity Framework (I won’t be discussing the pros and cons of doing so here!) and was using .Net Core for the API and therefore Entity Framework Core. I’d also implemented a generic repository and a Unit Of Work class which means all the repository contexts are saved at the same time.

Add a new record using EF Core

There’s plenty of code examples out there for how to add a record using Entity Framework, but this is how mine was implemented :

_unitOfWork.Product.Add(product);
_unitOfWork.Save();

We want to be able to add the product object to the database and then find out it’s id so that we can request the data.

Getting the object Id after .Save()

In this example the product object has been populated with all the data for your new product, let’s say Name, Description and Price. In the image below you can see the populated object properties, and also that although we’ve already called the _unitOfWork.Product.Add command, with a populated object, that the id of the entity is still 0.

Get the id after Entity Framework add

You can see from this image that the Description, Name and Price properties are all populated, and can also see the Id property as 0.

In the next image we’ve now executed the _unitOfWork.Save() command, and as soon as that has completed if you inspect the product object again you’ll see that the Id property is now populated. So the ID of the EF Core added entity is automatically updated once you’ve called the Save method on context.

Get new id after EF Core create new record

This is the relevant code within which I then use the new id to Get the object data to return in the endpoint response :

     var e = _unitOfWork.Product.Add(product);
     _unitOfWork.Save();

     return CreatedAtAction(nameof(GetProduct), new { productId = product.Id }, product);

Summary

If you are trying to find out how to retrieve the id of a newly created record using entity framework, then this post should have explained how to do so.