tags:

views:

784

answers:

2

I've a procedure where I need to save a entity object. The problem is that I don't know if this entity is attached to my datacontext or not. To solve this I use the following code:

    try
    {
        db.ClientUsers.Attach(clientUser);
        db.Refresh(RefreshMode.KeepCurrentValues, clientUser);
    }
    finally { }

    db.SubmitChanges();

I'm looking for a better method to detect if an entity belongs to a context and also to test if an entity is attached to a specific context.

+8  A: 

I wonder... what does GetOriginalEntityState return for a non-attached object? Even if it throws an exception, it'll probably be faster than a refresh...

(update) - a test shows it returns null:

        Customer cust = new Customer();
        Customer orig = ctx.Customers.GetOriginalEntityState(cust);
        Assert.IsNull(orig);

        cust = new Customer();
        ctx.Customers.Attach(cust);
        orig = ctx.Customers.GetOriginalEntityState(cust);
        Assert.IsNotNull(orig);
        Assert.AreNotSame(cust,orig);

So perhaps use GetOriginalEntityState and check for null returned value...

Marc Gravell
This is great! Makes for a nice "IsAttached(Of T)" extension method for DataContext.
rossisdead
A: 

I think a better solution is this:

ObjectStateEntry stateEntry = null;
if (context.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry))
{
    //you know you are attached!
}

Found on http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/49e97c25-7325-457a-891b-8fd58c726f3e.

Tillito