I am getting the following error when trying to attach an object that is already attached to a given context via context.AttachTo(...):
A
Try this extension method (this is untested and off-the-cuff):
public static bool IsAttachedTo(this ObjectContext context, object entity) {
if(entity == null) {
throw new ArgumentNullException("entity");
}
ObjectStateEntry entry;
if(context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry)) {
return (entry.State != EntityState.Detached);
}
return false;
}
Given the situation that you describe in your edit, you might need to use the following overload that accepts an EntityKey instead of an object:
public static bool IsAttachedTo(this ObjectContext, EntityKey key) {
if(key == null) {
throw new ArgumentNullException("key");
}
ObjectStateEntry entry;
if(context.ObjectStateManager.TryGetObjectStateEntry(key, out entry)) {
return (entry.State != EntityState.Detached);
}
return false;
}
To build an EntityKey in your situation, use the following as a guideline:
EntityKey key = new EntityKey("MyEntities.User", "Id", 1);
You can get the EntityKey from an existing instance of User by using the property User.EntityKey (from interface IEntityWithKey).