I've a procedure where I need to save an 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);
}
catch { }
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With