问题
I'm working with disconnected POCO objects.
When I persist a single object, it works fine!
The problem starts when I want to persist related objects.
For example:
Retrieving object from Data layer:
using (MyContext ctx = new MyContext ())
{
return ctx.Users.First();
}
This object goes back to Business layer and there, I add some child records, see below (just to ilustrate):
objectUser.Permissions.Add(new Permission());
objectUser.Permissions.Add(new Permission());
Permissions is a navigation to User Permissions.
And then, I want to persist this objectUser back to database, then I do:
using (MyContext ctx = new MyContext ())
{
ctx.Users.Attach(objectUser);
ctx.ObjectStateManager.ChangeObjectState(objectUser, System.Data.EntityState.Modified);
ctx.SaveChanges();
}
But on first line inside using, I get the error: "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key".
Does anyone know if I'm doing something wrong?
I just want to persist objects and their related objects.
Thanks for helping me.
Luiz Gustavo
I've tried to detach the entity, but in this case I loose all related objects, and I need these related objects so that I can add/remove.
After that, I wanted to persist them back to database.
Am I doing a stupid architecture??
Luiz Gustavo
回答1:
The issue here seems to be that the objectUser
object is still attached to the context used to retrieve it from the database. If you require this workflow where you have two different contexts defined you must detach the objectUser
from the initial context. One way to do this is to turn off object tracking on the objectUser
context object. Alternately you could manually detach the object from the context.
using (MyContext ctx = new MyContext ())
{
//EF 4.1 - ctx.Configuration.AutoDetectChangesEnabled = false;
ctx.Users.MergeOption = MergeOption.NoTracking;
return ctx.Users.First();
}
Blog: http://blogs.msdn.com/b/dsimmons/archive/2010/01/12/ef-merge-options-and-compiled-queries.aspx
Part 1 is all about the MergeOption property.
来源:https://stackoverflow.com/questions/8315654/persisting-disconnected-poco-entities