winforms An entity object cannot be referenced by multiple instances of IEntityChangeTracker
I am getting this error when trying to add multiple properties.
public NewPropertyHelper(DataLayer.IAccrualRe开发者_JAVA技巧pository Repository) {
this.SaveAction = Properties => {
foreach (Property P in Properties)
{
Repository.Properties.AddObject(P);
Repository.SaveChanges();
}
};
}
From what I can gather, the line
Repository.Properties.AddObject(P);
is attempting to add the object P to the current repository, and since you got it from a different repository you'd need to remove it (or detach it) from the other repository first.
EDIT: So I am assuming that somewhere in Repository, there is a wrapped DataContext (or maybe Repository inherits your DataContext. When you get an object from a DataContext, the object is constantly references by a change tracker, which keeps track of what needs to be sent back to the database if you update that object. Because you don't want to double-count any objects, EF prevents you from attaching that object to more than one data context at a time. Before you can attach the object to a new data context, you need to detach it from the DataContext that is already tracking it.
To do that, you need to call the Detach method on the object and any objects that it references that are also tracked by EF. A good example of how to do that is here: http://www.codeproject.com/KB/linq/linq-to-sql-detach.aspx
精彩评论