2

I have a create method where I add a new Employee Object to the database, after the employee is added I want to go into the edit page to be able to enter more details about the employee if I wish.

The Edit action method takes 1 parameter, the EmployeeID, however this EmployeeID is dynamically assigned by the database once an object is added to the Employee Table. How do I access the ID of the newly added employee after _db.SaveChanges() within the same action method?

here is what part of my method looks like:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee Employee) {
 _db.Employees.Add(Employee);
 _db.SaveChanges();
 //access the employee and gets its id???
 //var id = id???
 return RedirectToAction("EditEmployeeViewModel", new { id = id});
}
Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

2 Answers2

3

You could just use this:

Employee.Id

The Employee object is synchronized with the changes you make to the db. Hence, when you add this objects to the Employees and call the SaveChanges, this objects will be saved to the db and it's state will be updated, having the Id of the Employee.

Specifically, as it stated here:

Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when autogenerated Ids are used.

Community
  • 1
  • 1
Christos
  • 53,228
  • 8
  • 76
  • 108
2

try below code and access newest current employee Id like Employee.Id:-

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee Employee) {
 _db.Employees.Add(Employee);
 _db.SaveChanges();

 var id = Employee.Id;
 return RedirectToAction("EditEmployeeViewModel", new { id = id});
}
Neel
  • 11,625
  • 3
  • 43
  • 61