实体框架 - 拆卸实体时ObjectContext的处置? [英] Entity Framework - Detaching entities when ObjectContext disposed?

查看:116
本文介绍了实体框架 - 拆卸实体时ObjectContext的处置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是EF在WinForms应用程序,我的想法是让每笔交易的ObjectContext的,而不是一个长期运行的环境。但我发现了一个错误,当我尝试从previous交易对象附加到一个新的,是与实体已经在另一个上下文之中。

I'm using the EF in a WinForms app, my idea is to have an ObjectContext per transaction instead of a single long running context. But I'm getting an error when I try to attach objects from a previous transaction into a new one, something to do with the entity already being in another context.

我有点假设实体得到分离当对象范围内得到处理,这是不是这样? (也许是我没有正确处理上下文某处)。如果实体没有得到超脱,有没有这样的处理方式?

I kinda assumed that entities got detached when the object context gets disposed, is this not the case?? (Maybe I'm not disposing the context correctly somewhere). If entities don't get detached, is there a way of doing so at disposal?

修改

显然实体没有被上下文处理后分离为@ F.Aquino说,但是做这样的事情似乎工作。虽然我不知道这是处理单位的正确道路。也许有人可以对可能出现此的问题发表评论:

Apparently entities are not being detached after context disposal as @F.Aquino said, but doing something like this seems to work. Although I'm not sure if this is a correct way of handling entities. Maybe someone could comment on problems that might arise from this:

public void Attach(params EntityObject[] objects)
{
    foreach (EntityObject obj in objects)
    {
        ((IEntityWithChangeTracker)obj).SetChangeTracker(null);
        entities.Attach(obj);
    }
}

基本上,当我想重新安装一个实体背景下,我只是空实体的变更跟踪,然后只需将它连接到新的环境。它似乎很好地工作。

Basically when I want to reattach an entity to a context, I just null the entity's change tracker, and then just attach it to the new context. It seems to work fine.

推荐答案

您必须手动分离它们并牢记所有引用将被设置在过程中。有此伟大的神奇类与上重新附加实体EF 1,由马蒂厄Mezil所有的麻烦处理,用法是这样的:

You have to detach them manually and keep in mind all the references will be disposed in the process. There is this great magical class that deals with all the hassles on reattaching entities in EF 1, by Matthieu Mezil, usage would be something like:

public static EntityObject SaveOrUpdate(this EntityObject entity)
{
    using (MyEntities context = new MyEntities())
    {
        entity.AttachGraph(context, () => new MyEntities());
        context.SaveChanges();
        return entity;
    }
}

这篇关于实体框架 - 拆卸实体时ObjectContext的处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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