This error says that you are trying to attach an object to your context, but it is already bound to another.
My suspicion is that this is probably not a direct link, but perhaps one of the navigation properties in your context contains an object that is bound to a different context. In my opinion (from what you described), separate contexts should only be used in reality if they are disconnected object structures, for example, they do not have FK between contexts.
Another thing to avoid is to ensure that for each unit of work you use only one instance of each context. If you try to use an entity from another instance of the context, this error will also occur.
EDIT:
Identifiers are generally best used if you want to keep an area out of the current context. You can re-attach objects to EF so that you can add them as you describe, but you need to make sure the original context is deleted or the object is detached, and then manually attach it to the new context using the following:
public DbEntityEntry<T> EnsureAttachedEF(T entity) { var e = m_Context.Entry(entity); if (e.State == EntityState.Detached) { m_Context.Set<T>().Attach(entity); e = m_Context.Entry(entity); } return e; }
This, however, is quite a lot of work, so using identifiers is usually the best idea.
source share