Is is possible to check if an object is already attached to a data context in Entity Framework?

后端 未结 5 972
清歌不尽
清歌不尽 2020-11-28 04:26

I am getting the following error when trying to attach an object that is already attached to a given context via context.AttachTo(...):

A

5条回答
  •  臣服心动
    2020-11-28 05:02

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

提交回复
热议问题