Ben Foster
Ben Foster

Reputation: 34800

Entity Framework 4 - checking to see if an entity is attached

In NHibernate we override Equals() and GetHashCode() to calculate entity equality.

Is the same necessary in Entity Framework?

The reason I ask is we are using EF4 with POCOs and are in the process of implementing a caching layer. The problem we have is when checking to see if an item is already attached to the object context. Currently this evaluates to false, even when the entity already exists in the current object context.

Upvotes: 1

Views: 3184

Answers (1)

Aleksei Anufriev
Aleksei Anufriev

Reputation: 3236

Maybe this code will give you some ideas. Im not using POCOs, but common points are the same I think.

Here is sample Update method which checks if Context has entity attached before performing updating routine.

 public T Update(T entity)
 {
      if (entity == null) throw new ArgumentNullException("entity");
      var key = ObjectContext.CreateEntityKey(ObjectContext.GetEntitySet<T>().Name, entity);
      if (ObjectContext.IsAttached(key))
      {
          ObjectContext.ApplyCurrentValues(key.EntitySetName, entity);
      }
      else
      {
          ObjectContext.AttachTo(ObjectContext.GetEntitySet<T>().Name, entity);
          ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
      }
      return entity;
 }  



internal static EntitySetBase GetEntitySet<TEntity>(this ObjectContext context)
 {
      var container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
      var baseType = GetBaseType(typeof(TEntity));
      var entitySet = container.BaseEntitySets
                .Where(item => item.ElementType.Name.Equals(baseType.Name))
                .FirstOrDefault();

      return entitySet;
 }  

internal static bool IsAttached(this ObjectContext context, 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;
 }


  private static Type GetBaseType(Type type)
  {
       var baseType = type.BaseType;
       if (baseType != null && baseType != typeof(EntityObject))
       {
            return GetBaseType(type.BaseType);
       }
       return type;
  }

Hope this can help you a bit=)

Upvotes: 1

Related Questions