I get this error:
a different object with the same identifier value was already associated with the session: 63, of entity: Core.Domain.Model.Employee
Within my ASP.NET MVC controller actions I do this:
public ActionResult Index(int? page)
{
int totalCount;
Employee[] empData = _employeeRepository.GetPagedEmployees(page ?? 1, 5, out totalCount);
EmployeeForm[] data = (EmployeeForm[]) Mapper<Employee[], EmployeeForm[]>(empData);
PagedList<EmployeeForm> list = new PagedList<EmployeeForm>(data, page ?? 1, 5, totalCount);
if (Request.IsAjaxRequest())
return View("Grid", list);
return View(list);
}
public ActionResult Edit(int id)
{
ViewData[Keys.Teams] = MvcExtensions.CreateSelectList(
_teamRepository.GetAll().ToList(),
teamVal => teamVal.Id,
teamText => teamText.Name);
return View(_employeeRepository.GetById(id) ?? new Employee());
}
[HttpPost]
public ActionResult Edit(
Employee employee,
[Optional, DefaultParameterValue(0)] int teamId)
{
try
{
var team = _teamRepository.GetById(teamId);
if (team != null)
{
employee.AddTeam(team);
}
_employeeRepository.SaveOrUpdate(employee);
return Request.IsAjaxRequest() ? Index(1) : RedirectToAction("Index");
}
catch
{
return View();
}
}
Mapping files:
Employee
public sealed class EmployeeMap : ClassMap<Employee>
{
public EmployeeMap()
{
Id(p => p.Id)
.Column("EmployeeId")
.GeneratedBy.Identity();
Map(p => p.EMail);
Map(p => p.LastName);
Map(p => p.FirstName);
HasManyToMany(p => p.GetTeams())
.Access.CamelCaseField(Prefix.Underscore)
.Table("TeamEmployee")
.ParentKeyColumn("EmployeeId")
.ChildKeyColumn("TeamId")
.LazyLoad()
.AsSet()
.Cascade.SaveUpdate();
HasMany(p => p.GetLoanedItems())
.Access.CamelCaseField(Prefix.Underscore)
.Cascade.SaveUpdate()
.KeyColumn("EmployeeId");
}
}
Team:
public sealed class TeamMap : ClassMap<Team>
{
public TeamMap()
{
Id(p => p.Id)
.Column("TeamId")
.GeneratedBy.Identity();
Map(p => p.Name);
HasManyToMany(p => p.GetEmployees())
.Access.CamelCaseField(Prefix.Underscore)
.Table("TeamEmployee")
.ParentKeyColumn("TeamId")
.ChildKeyColumn("EmployeeId")
.LazyLoad()
.AsSet()
.Inverse()
.Cascade.SaveUpdate();
}
}
How do I fix this bug and what is the problem here?