"An entity object cannot reference multiple instances of IEntityChangeTracker."

I am using the MYSql server as the database outside my window. In my db there are two schemes in which I have to insert records. I created two context objects, one for each scheme. When I use contextA, which is located in schema1, all writes are fine, but when I use contextB, I get this exception. This has something to do with MySql Driver.

+4
source share
3 answers

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.

+9
source

This is almost certainly caused by proxies and change tracking. Disable these features in both constructors and see if it solves your problem.

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

Moving a comment in anwser:

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

You can use the NoTracking parameter in EF to stop EF from caching an object if you work with it out of context.

+2
source

Source: https://habr.com/ru/post/1484578/


All Articles