I have a web application in .net 4.5.1 with MVC and entity framework.
The error occurs in a basic CRUD.
I retrieve the object that will be the model sent to the view with the following code:
Professor professor = db.Pessoa
.Include(p => p.Agenda)
.Include(p => p.Contato)
.Include(p => p.Endereco)
.Include(p => p.SocioEconomico)
.Include(p => p.SocioEconomico.TelefoneMae)
.Include(p => p.SocioEconomico.TelefonePai)
.Include(p => p.Contato.Telefones)
.Where(p => p is Professor)
.Single(p => p.Id == id.Value) as Professor;
This object is sent to the view and then I get the POST with the purpose of updating one or more fields.
In POST it has the following code:
db.Entry(professor).State = EntityState.Modified;
db.SaveChanges();
But when I pass the tem that changes the entity's status to "Modified" I get the following exception:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager can not track multiple objects with the same key.
If I retrieve the "Teacher" using the Find professor = db.Find(id)
method, the update works correctly, but I do not have the "child" objects of it.
I have seen several possible solutions, but none worked. Has anyone had the same problem and can you tell me the error?
Adding all controller methods definition as required
GET
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Professor professor = db.Pessoa
.Include(p => p.Agenda)
.Include(p => p.Contato)
.Include(p => p.Endereco)
.Include(p => p.SocioEconomico)
.Include(p => p.SocioEconomico.TelefoneMae)
.Include(p => p.SocioEconomico.TelefonePai)
.Include(p => p.Contato.Telefones)
.Where(p => p is Professor)
.Single(p => p.Id == id.Value) as Professor;
if (professor == null)
{
return HttpNotFound();
}
return View(professor);
}
POST
public ActionResult Edit(Professor professor)
{
if (ModelState.IsValid)
{
db.Entry(professor).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(professor);
}