views:

260

answers:

1

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 dont 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)
        {
            (obj as IEntityWithChangeTracker).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.

+1  A: 

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;
    }
}
F.Aquino