实体对象不能被 IEntityChangeTracker 的多个实例引用

发布于 2024-12-13 02:03:24 字数 744 浏览 3 评论 0原文

我有一个名为 Message 的模型。在该模型中,有另一个名为 Resource 的模型的 ICollection ResourceSubscribers。当我尝试

public void SaveMessage(List<int> subscribers)
    {
        Condition.Requires(model).IsNotNull();
        Message model = new Message();

        //Some assignments to initialize the model

        ICollection<Resource> res = new List<Resource>();

        foreach (var item in subscribers)
        {
            res.Add(this.ResourceService.GetResourceById(item));
        }

        model.ResourceSubscribers = res;
        Context.Messages.Add(model);
        Context.SaveChanges();
    }

“Context.Messages.Add(model);” 时该行抛出 InvalidOperationException 并显示消息“实体对象不能被 IEntityChangeTracker 的多个实例引用。”。

I have a model called Message. In the model there is a ICollection ResourceSubscribers of another model called Resource. When I try to

public void SaveMessage(List<int> subscribers)
    {
        Condition.Requires(model).IsNotNull();
        Message model = new Message();

        //Some assignments to initialize the model

        ICollection<Resource> res = new List<Resource>();

        foreach (var item in subscribers)
        {
            res.Add(this.ResourceService.GetResourceById(item));
        }

        model.ResourceSubscribers = res;
        Context.Messages.Add(model);
        Context.SaveChanges();
    }

the "Context.Messages.Add(model);" line throws an InvalidOperationException with message "An entity object cannot be referenced by multiple instances of IEntityChangeTracker.".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

野稚 2024-12-20 02:03:24

如果您使用相同的上下文,最好将上下文用作单例实例。

这将确保一个类只有一个实例并提供对其的全局访问点

检查: http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1

If you use same Context any where better to use context as singleton instance.

This will Ensure a class has only one instance and provide a global point of access to it

Check this: http://www.dofactory.com/Patterns/PatternSingleton.aspx#_self1

烟柳画桥 2024-12-20 02:03:24

您是否在 GetResourceById 中使用另一个上下文来获取资源?在这种情况下,这些对象与该上下文相关联。在执行 Context.Messages.Add 时,您尝试将对象与另一个不允许的上下文关联。

所有一起发生的相关操作应该使用相同的上下文。拥有多个上下文就会带来问题。

Are you using another context in GetResourceById to get the resources? In that case those objects are associated with that context. When doing Context.Messages.Add you try to associated the objects with another context which is not allowed.

All related operations that take place together should use the same context. Having multiple contexts around is asking for problems.

梨涡少年 2024-12-20 02:03:24

这是一个老问题,但我想我会发布我的答案,以防它对某人有帮助。

正如 Elad Benda 提到的,我在 MVC 代码中遇到了同样的问题,甚至使用工作单元模式也是如此。我发现我的 DbContext 资源在控制器调用结束时没有被释放。

    using (_DatabaseUow)
    {
        // your controller code that accesses the database here.
    } // When this goes out of scope dispose is called.

然后Dispose DatabaseUnitOfWork 类

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing == true)
        {
            _ObdDbContext.DetachAll();
            _ObdDbContext = null;
            _ObdBusinessData = null;
        }
    }

    ~DatabaseUnitOfWork()
    {
        Dispose(false);
    }

_ObdBusinessData 成员类似于存储库。最后,DbContext 派生类中的 DetachAll() 方法如下所示:

    public void DetachAll()
    {
        var entries = SetTestsOnlineData.Local;
        while (entries.Count != 0)
        {
            TestsOnlineData tod = entries[0];
            Tests tro = entries[0].Tests;
            List<TestsDtc> dtcs = entries[0].Tests.TestsDtcs.ToList();

            foreach (TestsDtc dtc in dtcs)
                Detach(dtc);
            Detach(entries[0].Tests);
            Detach(entries[0]);

            tro.TestsDtcs = dtcs;
            tro.TestsOnlineData = tod;
            tod.Tests = tro;
        }
    }

    public void Detach(object entity)
    {
        ((IObjectContextAdapter)this).ObjectContext.Detach(entity);
    }

我使用实体/对象的特定知识来分离内存中的所有内容。我有一个名为 TestsOnlineData 的表。它链接到 Tests,而 Tests 又链接到 TestsDtc 列表。请注意,我保留了这些链接关系,因为我的对象树的根将被保留,但 DbContext 将在其他链接关系分离时释放它们。

我本来想让它更通用,但这有效。我希望这有帮助。

It's an old question, but I thought I'd post my answer in case it helps someone.

I came across this same problem in my MVC code, even using the Unit of Work pattern, as mentioned by Elad Benda. I discovered my DbContext resource was not being released at the end of the controller call.

    using (_DatabaseUow)
    {
        // your controller code that accesses the database here.
    } // When this goes out of scope dispose is called.

Then Dispose the DatabaseUnitOfWork class

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing == true)
        {
            _ObdDbContext.DetachAll();
            _ObdDbContext = null;
            _ObdBusinessData = null;
        }
    }

    ~DatabaseUnitOfWork()
    {
        Dispose(false);
    }

The _ObdBusinessData member is similar to a repository. Finally the DetachAll() method in the DbContext derived class looks like this:

    public void DetachAll()
    {
        var entries = SetTestsOnlineData.Local;
        while (entries.Count != 0)
        {
            TestsOnlineData tod = entries[0];
            Tests tro = entries[0].Tests;
            List<TestsDtc> dtcs = entries[0].Tests.TestsDtcs.ToList();

            foreach (TestsDtc dtc in dtcs)
                Detach(dtc);
            Detach(entries[0].Tests);
            Detach(entries[0]);

            tro.TestsDtcs = dtcs;
            tro.TestsOnlineData = tod;
            tod.Tests = tro;
        }
    }

    public void Detach(object entity)
    {
        ((IObjectContextAdapter)this).ObjectContext.Detach(entity);
    }

I used specific knowledge of my entities/objects to detach everything in memory. I have a table called TestsOnlineData. It links to Tests which links to a list of TestsDtc. Notice, I preserve those link relationships since the root of my object tree will be preserved, but the DbContext will release the others when they are detached.

I would have liked to make this more generic, but this worked. I hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文