简体   繁体   中英

“An entity object cannot be referenced by multiple instances of IEntityChangeTracker.”

I am using MYSql server as a database behind my windows form application. There are two schemas in my db that I have to throw entries into. I have created two context objects one for each schema. When I use contextA which is on schema1 all the entries are done perfectly but when I use contextB I get this exception. Does it have something to do with MySql Driver.

This error says you are trying to attach an entity to your context but its already attached to another one.

My suspicion is that this is probably not a direct reference but perhaps one of the navigation properties on your context contains an entity which is attached to the other context. In my opinion (from what you have described) seperate contexts should only really be used if they are disconnected object structures, eg they have no FKs between the contexts.

The other thing to avoid is to ensure that for each unit of work you only use one instance of each context. If you try and use an entity from another context instance this error will also occur.

EDIT:

IDs are generally a better idea to use if you want to maintain scope outside of the current context. You can reattach entities to EF so you can add them in the way you are describing but you have to make sure the original context is disposed or the entity is detached and then manually attach it to the new context with something like 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 bit of work so using IDs is generally a better idea.

It is almost certainly caused by proxies and change tracking. Disable these features in both constructors and see if it resolves your issue.

public class contextA : DbContext
{
   public contextA()
   {
      Configuration.ProxyCreationEnabled = false;
   }
}

Moving comment to anwser:

It seems you maybe working with the entity outside of the EF context. This would cause the changes to the entity to not be tracked. At the same time, EF would cache this entity and if you try to attach the entity to the context, it will see it already exists and will throw an error.

You could use the NoTracking option in EF to stop EF from caching the entity if you are working with it outside of the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM