I am using Entity Framework 4.0. I am facing problem while updating data in the database. I am getting this exception :
An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same key.
I am working on the relational database. The following are 3 entities and there relation :
1 to * 1 to *
Ceremony -----------> Menu ------------> CourseOption
Everything works fine, if I update the ceremony which already contains the Menus
and CourseOptions
. The problem comes when we insert new Menu
and CourseOption
entry in the ceremony at the time of update. Than I got the above mention exception.
C# code to update existing ceremony
public HttpResponseMessage PutCeremony(int id, Ceremony ceremony)
{
if (ModelState.IsValid && id == ceremony.Id)
{
db.Entry(ceremony).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, ceremony);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
How can I get rid of this problem? Please help
EDIT
Today i spend a whole day in this, i read a lot of articals and stackoverflow question. I found that once a product is fetched from the Context, the context is keeping track of it
so that why instead of using :
db.Entry(ceremony).State = EntityState.Modified;
I used
db.Entry(db.Ceremonies.Find(ceremony.Id)).CurrentValues.SetValues(ceremony);
Now by doing this change the exception gone and Ceremony entity properties are changing properly. But the ceremony related Menus entry and CourseOptions entry are not updating. Please give me suggestion guys. I am absolutely new in EF.