“实体对象不能由IEntityChangeTracker的多个实例引用。” [英] "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."

查看:80
本文介绍了“实体对象不能由IEntityChangeTracker的多个实例引用。”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将MYSql服务器用作Windows窗体应用程序后面的数据库。我的数据库中有两个架构,我必须将条目放入其中。我为每个模式创建了两个上下文对象。当我使用位于schema1上的contextA时,所有输入均已完美完成,但是当我使用contextB时,出现此异常。
它与MySql驱动程序有关。

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.

我怀疑这可能不是直接引用,但您上下文中的一个导航属性可能包含一个附加到另一个上下文的实体。我认为(根据您的描述),仅当分离的上下文是断开连接的对象结构时才应真正使用它们,例如,它们在上下文之间没有FK。

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.

编辑:

ID如果要在当前上下文之外维护范围,通常是一个更好的主意。您可以将实体重新附加到EF,以便您可以按照描述的方式添加它们,但必须确保原始上下文已被处置或实体已分离,然后使用类似以下内容的方法将其手动附加到新上下文:

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;
    }

但是这是很多工作,因此使用ID通常是一个更好的主意

This however is quite a bit of work so using IDs is generally a better idea.

这篇关于“实体对象不能由IEntityChangeTracker的多个实例引用。”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆