Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if entity is attached to a datacontext

Tags:

c#

linq-to-sql

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.

like image 389
Niels Bosma Avatar asked Feb 09 '09 11:02

Niels Bosma


1 Answers

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...

like image 135
Marc Gravell Avatar answered Sep 25 '22 01:09

Marc Gravell