Example #1
0
        /// <summary>
        ///     If entity with the same key already in the ObjectContext, returns that entity.
        ///     Otherwise attaches passed entity and returns it.
        /// </summary>
        /// <typeparam name="TEntity">Entity with key</typeparam>
        /// <param name="db">EF ObjectContext</param>
        /// <param name="entity">Entity with key specified to attach or find loaded entity with the same key.</param>
        /// <returns></returns>
        public static TEntity GetOrAttach <TEntity>(this ObjectContext db, TEntity entity)
            where TEntity : class, IEntityWithKey
        {
            if (entity == null)
            {
                return(null);
            }

            if (db == null)
            {
                throw new ArgumentNullException("db");
            }

            ObjectStateEntry entry;

            if (db.ObjectStateManager.TryGetObjectStateEntry(entity, out entry))
            {
                TEntity loadedEntity = (TEntity)entry.Entity;
                if (entry.State == EntityState.Detached)
                {
// ReSharper disable once AssignNullToNotNullAttribute
                    db.Attach(loadedEntity);
                }
                return(loadedEntity);
            }

            db.Attach(entity);
            return(entity);
        }
Example #2
0
        public static bool TryAttach(this ObjectContext context, IEntityWithKey entity)
        {
            bool             attached = false;
            ObjectStateEntry entry;

            if (entity != null && !context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry))
            {
                context.Attach(entity);
                attached = true;
            }
            return(attached);
        }
Example #3
0
        public void Attach(ref T entityWithKey)
        {
            entityWithKey.EntityKey = objectContext.CreateEntityKey(typeof(T).Name, entityWithKey);
            object entityRef = entityWithKey;

            if (objectContext.TryGetObjectByKey(entityWithKey.EntityKey, out entityRef))
            {
                entityWithKey = (T)entityRef;
            }
            else
            {
                objectContext.Attach(entityWithKey);
            }
        }
Example #4
0
    public static void ApplyDetachedPropertyChanges <T>(this ObjectContext db, T entity, Func <T, int> getIdDelegate)
        where T : EntityObject
    {
        var entitySetName = db.DefaultContainerName + "." + entity.GetType().Name;
        var id            = getIdDelegate(entity);
        var entityKey     = new EntityKey(entitySetName, "Id", id);

        db.Attach(new Department {
            Id = id, EntityKey = entityKey
        });
        db.AcceptAllChanges();

        db.ApplyPropertyChanges(entitySetName, entity);
    }
Example #5
0
        public static void Update(this ObjectContext context, string entitySetName, EntityObject entity)
        {
            if (entity.EntityKey == null)
            {
                entity.EntityKey = context.CreateEntityKey(entitySetName, entity);
            }
            if (entity.EntityState == System.Data.EntityState.Detached)
            {
                context.Attach(entity);
            }
            var stateEntry       = context.ObjectStateManager.GetObjectStateEntry(entity.EntityKey);
            var propertyNameList = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select(pn => pn.FieldType.Name);

            foreach (var propName in propertyNameList)
            {
                stateEntry.SetModifiedProperty(propName);
            }
        }
    public static void ApplyDetachedPropertyChanges <T>(this ObjectContext db, T entity, Func <T, int> getIdDelegate)
        where T : EntityObject
    {
        var entitySetName = db.DefaultContainerName + "." + entity.GetType().Name;

        T newEntity = Activator.CreateInstance <T>();

        newEntity.EntityKey = db.CreateEntityKey(entitySetName, entity);

        Type t = typeof(T);

        foreach (EntityKeyMember keyMember in newEntity.EntityKey.EntityKeyValues)
        {
            PropertyInfo p = t.GetProperty(keyMember.Key);
            p.SetValue(newEntity, keyMember.Value, null);
        }
        db.Attach(newEntity);
        //db.AcceptAllChanges();
        db.ApplyPropertyChanges(entitySetName, entity);
    }
Example #7
0
        /// <summary>
        /// attache entity as unchanged
        /// </summary>
        /// <typeparam name="T">entity type</typeparam>
        /// <param name="context">object context</param>
        /// <param name="entity">entity to be attached</param>
        /// <returns>attached entity</returns>
        public static T AttachExistedEntity <T>(this ObjectContext context, T entity)
            where T : EntityObject
        {
            EdmEntityTypeAttribute entityTypeAttr = (EdmEntityTypeAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(EdmEntityTypeAttribute), false);

            if (entityTypeAttr == null)
            {
                throw new NotSupportedException("T is not an entity.");
            }
            string entityFullname = context.DefaultContainerName + "." + entityTypeAttr.Name;

            entity.EntityKey = new System.Data.EntityKey(entityFullname,
                                                         from p in typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)
                                                         where p.GetGetMethod(false) != null
                                                         let attribute = (EdmScalarPropertyAttribute)Attribute.GetCustomAttribute(p, typeof(EdmScalarPropertyAttribute))
                                                                         where attribute != null && attribute.EntityKeyProperty
                                                                         select new KeyValuePair <string, object>(p.Name, p.GetValue(entity, null)));
            context.Attach(entity);
            context.ApplyPropertyChanges(entityTypeAttr.Name, entity);
            return(entity);
        }
Example #8
0
 /// <summary>
 /// Deletes this document from the database.
 /// </summary>
 public void Delete <T>(T item) where T : class, IRepoData, new()
 {
     db.Attach(item.CastTo <IEntityWithKey>());
     db.DeleteObject(item);
 }
Example #9
0
        public static void AttachAsModified(this ObjectContext context, EntityObject current, EntityObject original)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (current == null)
            {
                throw new ArgumentNullException("current");
            }
            if (original == null)
            {
                throw new ArgumentNullException("original");
            }
            if (current.EntityState != EntityState.Detached)
            {
                context.Detach(current);
            }
            Type       entityType = current.GetType();
            EntityType type       = EntityHelper.GetEntityType(context, entityType);

            PropertyInfo[] source = type.Properties.Select <EdmProperty, PropertyInfo>(delegate(EdmProperty p)
            {
                return(entityType.GetProperty(p.Name));
            }).Where <PropertyInfo>(delegate(PropertyInfo p)
            {
                return(p != null);
            }).ToArray <PropertyInfo>();
            PropertyDescriptor[] descriptorArray = type.NavigationProperties.Select <NavigationProperty, PropertyDescriptor>(delegate(NavigationProperty p)
            {
                return(TypeDescriptor.GetProperties(entityType)[p.Name]);
            }).Where <PropertyDescriptor>(delegate(PropertyDescriptor p)
            {
                return(!typeof(IEnumerable).IsAssignableFrom(p.PropertyType));
            }).ToArray <PropertyDescriptor>();
            PropertyDescriptor[] descriptorArray2 = descriptorArray.Select <PropertyDescriptor, PropertyDescriptor>(delegate(PropertyDescriptor p)
            {
                return(EntityHelper.GetReferenceProperty(p));
            }).ToArray <PropertyDescriptor>();
            object[] objArray = source.Select <PropertyInfo, object>(delegate(PropertyInfo p)
            {
                return(p.GetValue(current, null));
            }).ToArray <object>();
            EntityKey[] keyArray = descriptorArray2.Select <PropertyDescriptor, EntityReference>(delegate(PropertyDescriptor p)
            {
                return((EntityReference)p.GetValue(current));
            }).Select <EntityReference, EntityKey>(delegate(EntityReference p)
            {
                if (p == null)
                {
                    return(null);
                }
                return(p.EntityKey);
            }).ToArray <EntityKey>();
            for (int i = 0; i < source.Length; i++)
            {
                source[i].SetValue(current, source[i].GetValue(original, null), null);
            }
            for (int j = 0; j < descriptorArray2.Length; j++)
            {
                EntityReference reference  = (EntityReference)descriptorArray2[j].GetValue(current);
                EntityReference reference2 = (EntityReference)descriptorArray2[j].GetValue(original);
                EntityKey       entityKey  = reference2.EntityKey;
                EntityObject    obj2       = (EntityObject)descriptorArray[j].GetValue(current);
                if ((obj2 != null) && (obj2.EntityKey != entityKey))
                {
                    descriptorArray[j].SetValue(current, null);
                }
                reference.EntityKey = entityKey;
            }
            context.Attach(current);
            for (int k = 0; k < source.Length; k++)
            {
                PropertyInfo info2 = source[k];
                object       objA  = objArray[k];
                object       objB  = info2.GetValue(original, null);
                if (!object.Equals(objA, objB))
                {
                    info2.SetValue(current, objA, null);
                }
            }
            for (int m = 0; m < descriptorArray2.Length; m++)
            {
                EntityReference reference3 = (EntityReference)descriptorArray2[m].GetValue(current);
                EntityKey       key2       = keyArray[m];
                if (!object.Equals(reference3.EntityKey, key2))
                {
                    reference3.EntityKey = key2;
                }
            }
        }