Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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.

like image 582
Hina Avatar asked Dec 06 '22 07:12

Hina


1 Answers

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.

like image 133
Not loved Avatar answered Dec 09 '22 14:12

Not loved