views:

87

answers:

2

I'm having a bit of trouble getting my head around when entities are attached and change tracked and when they are not. Sorry if this has already been asked. Say I have some code like this:

public MyEntity GetEntity()
{
    using (var ctx = new MyObjectContext)
    {
        return ctx.MyEntitySet.First();
    }
}

Then I call it

var result = GetEntity();

Should result be attached or detached from the context?

I was under the impression that when the ObjectContext got disposed the entity lost its change tracking. Or is the Context never getting disposed.

A: 

The attachment of the object isn't directly related to the context in my understanding. I believe that if the entity keys are set then it is still attached. You can detach the object, but you have to do it manually using the Detach method.

If you're after a detached object, try detaching it manually. Otherwise what you have done should allow you to update the object and save the changes without re-attaching the object.

Cheers

Odd
+1  A: 

If you write that code while the ctx has been disposed, because you didn't detach the entity from the ctx you can't attach it to another context. Essentially there remains a backpointer from the Entity to the ctx, which stops that from happening.

I suppose you could say it is 'psuedo-attached'.

Hope this helps

Alex James

Program Manager Entity Framework Team

Alex James