实体框架 - 当ObjectContext处理时分离实体? [英] Entity Framework - Detaching entities when ObjectContext disposed?

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

问题描述

我在WinForms应用程序中使用EF,我的想法是每个事务都有一个ObjectContext,而不是一个长时间运行的上下文。但是,当我尝试将上一个事务中的对象附加到一个新事物中时,我收到一个错误,与已经在另一个上下文中的实体有关。



I有点假设当对象上下文被处理时,实体分离,是不是这样? (也许我没有正确处理上下文)。如果实体没有分离,有没有办法这样做?



编辑



@ F.Aquino表示,实体在上下文处理后没有被分离,但是这样做似乎似乎有效。虽然我不知道这是否是正确的处理实体的方式。也许有人可以评论可能由此产生的问题:

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

基本上,当我想将一个实体重新连接到一个上下文我只是将实体的变更跟踪器置零,然后将其附加到新的上下文中。它似乎工作正常。

解决方案

你必须手动分离它们,并记住所有的引用将被处理。有这个伟大的魔法课程处理所有的麻烦重新附加在EF 1的实体,由Matthieu Mezil,使用将是这样的:

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


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?

EDIT

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.

解决方案

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天全站免登陆