Wednesday, 11 September 2013

Why two records are inserted when i try to insert Employee object which has Manager of type Employee?

Why two records are inserted when i try to insert Employee object which
has Manager of type Employee?

I have a classes as:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Employee Manager { get; set; }
public virtual Department Deptartment { get; set; }
}
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
Code to create new employee in controller: This code inserts two records
in DB.
[HttpPost]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}
I am providing MVC4 view for creating a new employee where user enter Name
of employee and ManagerId. When I get the posted Employee object, it has
Manager object with Id entered by user. However other details like Name is
null for that object where as Employee with that userId exist in database.
While inserting the Employee record in db, application is inserting two
records (one for employee name entered by user and other for manager Id
provided by user for that employee. For send, name is saved as null). Why
two records are inserted?

No comments:

Post a Comment