Getting Id of the newly created object with EF

1.1k Views Asked by At

My repository is being exposed through UnitOfWork and Add method have only following code:

public void Add(Employee emp)
{
    context.add(emp);
} 

Then, from UnitOfWork, i am calling the Add() method with this code:

this.UnitOfWork.EmployeeRepository.Create(emp);
this.UnitOfWork.Commit(); // This calls SaveChanges() EF method

Now the issue is how can i obtain the Id of newly created object here?

2

There are 2 best solutions below

0
On

After SaveChanges the employee entity wil have the new id assigned. Find a way to return it to higher level methods.

2
On

Normally if your Id is Identity, when you save changes the Id will be automatically filled.

context.Employees.Add(emp);
context.SaveChanges();
var newId=emp.Id; //The Id is filled after save changes

A second variant could be using the GetDatabaseValues method:

context.Entry(emp).GetDatabaseValues();
var id = emp.Id;