Hello,
I'm using .NET 3.5 SP1 in ASP.NET MVC application.
While using ObjectContext with Http Request lifetime, and trying to attach an entity ALREADY present in context, we get error: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key." For Example, the code :
Category newCategory = new Category {CategoryId = CategoryIdSelected};
ctx.AttachTo("CategorySet", newCategory);
will give error if 'Category' with CategoryId = CategoryIdSelected exists in ObjectContext.
Modified code to check for existing entity:
Category newCategory = new Category {CategoryId = CategoryIdSelected};
ObjectStateEntry stateEntry = null;
if( ctx.ObjectStateManager.TryGetObjectStateEntry(newCategory, out stateEntry)){
//EntityObject already attached in context, get it
newCategory = (EntityObject)stateEntry.Entity;
}else{
ctx.AttachTo("CategorySet", newCategory);
}
The modified code is still giving same error: "[System.InvalidOperationException] = {"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."
Please advise ?
Thank You