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

c# entity-framework

Question

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.

1
4
6/5/2013 6:00:00 PM

Popular Answer

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.

9
6/5/2013 7:58:20 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow