开发者

Entity Framework - Detaching entities when ObjectContext disposed?

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 gettin开发者_StackOverflowg 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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜