I'm using asp.net mvc to make a simple application where i have 3 pages divisions, employees and coffees.
database models
public abstract class BaseModel
{
[Key]
public int Id { get; set; }
}
public class Division : BaseModel
{
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee : BaseModel
{
public string Name { get; set; }
public string FamilyName { get; set; }
public string Function { get; set; }
public Division Division { get; set; }
public virtual ICollection<CoffeeBehavior> CoffeeBehaviors { get; set; }
}
frontend viewmodels
public class DivisionViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public List<EmployeeViewModel> Employees { get; set; }
}
public class EmployeeViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string FamilyName { get; set; }
public string Function { get; set; }
public DivisionViewModel Division { get; set; }
//public List<CoffeeBehaviorViewModel> CoffeeBehaviors { get; set; }
public int SelectedId { get; set; }
public List<DivisionListViewModel> divisions = new List<DivisionListViewModel>();
public IEnumerable<SelectListItem> DivisionItems => new SelectList(divisions, "Id", "Name");
}
i can create divisions edit them whatsoever. However when i create an employee this results in a duplicate enty for divisions in my database.
instead of adding the employee to my existing division a new division is created with the same name and the employee is added to that one
[HttpPost]
public ActionResult Create(EmployeeViewModel employee)
{
if (ModelState.IsValid)
{
employee.Division = divisionService.GetDivision(employee.SelectedId);
DivisionViewModel dv = divisionService.GetDivision(employee.SelectedId);
employee.Id = employeeService.Create(employee);
dv.Employees.Add(employee);
divisionService.Edit(dv);
return RedirectToAction("Index");
}
return View(employee);
}
this is the create method. i figured it was because the employee didn't have a generated key yet so i created the employee first and then added it to the division followed by updating the divison in the database.
this resulted in the same duplication but i received an error on updating the division
Attaching an entity of type 'CoffeeManager.DAL.Models.Division' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
i know i'm missing something but i have no clue what it is.