/// <summary> /// Apply the changes made to a detached entity /// </summary> /// <param name="pDbContext">DB Context</param> /// <param name="pEntity">Entity</param> public static void ApplyEntityChanges <T>(this DbContext pDbContext, T pEntity) where T : class { object original = null; try { if (pEntity != null) { DbEntityEntry <T> entry = pDbContext.Entry <T>(pEntity); if (entry != null && entry.State == EntityState.Detached) { ObjectContext objectContext = (pDbContext as IObjectContextAdapter).ObjectContext; ObjectSet <T> objectSet = objectContext.CreateObjectSet <T>(); EntityKey entitySetKey = objectSet.BuildEntityKey(pEntity); if (objectContext.TryGetObjectByKey(entitySetKey, out original)) { objectContext.ApplyCurrentValues(objectSet.GetEntitySetFullName(), pEntity); } } } } catch { throw; } }
/// <summary> /// Use this to query the database with LINQ. /// NOTE: Some operations may not be supported directly on the database. If you continue to /// get errors on a query, try doing .ToList() first and performing the query in memory. /// </summary> /// <typeparam name="T">The class of the object that you want to query.</typeparam> /// <returns>A LINQ query compatible object.</returns> public T Save <T>(ref T item) where T : class, IRepoData, new() { T retval = null; object oldItem = null; var setName = db.CreateObjectSet <T>().EntitySet.Name; EntityKey itemID = item.CastTo <EntityObject>().EntityKey ?? db.CreateEntityKey(setName, item); if (db.TryGetObjectByKey(itemID, out oldItem)) { var existingItem = oldItem.CastTo <T>(); if (oldItem.IsNotNull() && existingItem.Timestamp.DropMillisecods() > item.Timestamp.DropMillisecods()) { retval = existingItem; } else { item.Timestamp = DateTime.Now; db.ApplyCurrentValues(setName, item); } } else { item.Timestamp = DateTime.Now; db.AddObject(setName, item); } return(retval); }
private void GenericUpdateEntityCollection <T>(EntityCollection <T> collection, ObjectContext dbContext) where T : EntityObject, new() { int count = collection.Count(); int current = 0; List <T> collectionItemList = collection.ToList(); bool isAdded = false; while (current < count) { Object obj = null; dbContext.TryGetObjectByKey(collectionItemList[current].EntityKey, out obj); if (obj == null) { obj = new AgentAirlineMappings(); ((T)obj).EntityKey = collectionItemList[current].EntityKey; dbContext.AddObject(((T)obj).EntityKey.EntitySetName, obj); dbContext.TryGetObjectByKey(collectionItemList[current].EntityKey, out obj); dbContext.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Modified); collection.CreateSourceQuery().Context.ObjectStateManager.ChangeObjectState(collectionItemList[current], System.Data.EntityState.Modified); isAdded = true; } if (obj != null) { dbContext.ApplyCurrentValues <T>(((T)obj).EntityKey.EntitySetName, collectionItemList[current]); if (isAdded) { dbContext.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Added); collection.CreateSourceQuery().Context.ObjectStateManager.ChangeObjectState(collectionItemList[current], System.Data.EntityState.Added); } } current++; } }
public virtual void Update(T entity) { CompleteValidate(entity); entity = UpdateRule(entity); _context.ApplyCurrentValues <T>(entity.GetType().Name, entity); }
private static void Manter(ObjectContext context, string nomeTipo, Entidade item) { if (item.Id == 0) { context.AddObject(nomeTipo, item); } else { context.ApplyOriginalValues(nomeTipo, context.GetObjectByKey(context.CreateEntityKey(nomeTipo, item))); context.ApplyCurrentValues(nomeTipo, item); } }
public virtual void Modificar <T>(T entity) where T : EntityObject { //model.GetObjectByKey(entity.EntityKey); var orginalEntity = Get <T>(GetKeyPropertyValue <T>(entity)); model.ApplyCurrentValues <T>(string.Format("{0}Set", entity.GetType().Name), entity); model.SaveChanges(); // ORIGNIAL model.ApplyCurrentValues<entity as entity.GetType()>(string.Format("{0}Set", entity.GetType().Name), entity); //var orginalEntity = Get<T>(GetKeyPropertyValue<T>(entity)); //model.ApplyPropertyChanges(GetEntitySetName<T>(), entity); //model.SaveChanges(); }
public void Update <TEntity>(TEntity entity) where TEntity : class { var fqen = GetEntityName <TEntity>(); object originalItem; EntityKey key = ObjectContext.CreateEntityKey(fqen, entity); if (ObjectContext.TryGetObjectByKey(key, out originalItem)) { ObjectContext.ApplyCurrentValues(key.EntitySetName, entity); } }
public void Update(T entity) { // use our method to get the entity set name var entityES = GetEntitySet(entity); // create the entity key var key = _context.CreateEntityKey(entityES.Name, entity); // retrieve and update the item _context.GetObjectByKey(key); _context.ApplyCurrentValues(entityES.Name, entity); _context.SaveChanges(); }
public virtual void Update(T entity) { if (entity == null) { throw new ArgumentNullException("entity"); } EntityKey key = GenerateKey(entity); var originalEntity = (T)_context.GetObjectByKey(key); string qualifiedEntitySetName = this.GetEntitySetName(typeof(T)); Type parentType = entity.GetType(); this.SetInsertAuditInfo(entity, originalEntity, parentType); _context.ApplyCurrentValues(qualifiedEntitySetName, entity); }
private static void AttachUpdated(this ObjectContext context, EntityObject entityModified) { if (entityModified.EntityState == EntityState.Modified) { object original = null; if (context.TryGetObjectByKey(entityModified.EntityKey, out original)) { context.ApplyCurrentValues(entityModified.EntityKey.EntitySetName, entityModified); } else { throw new ObjectNotFoundException(); } } }
public static void AttachUpdated(this ObjectContext objContext, EntityObject objDetached) { if (objDetached.EntityState == EntityState.Detached) { object original = null; if (objContext.TryGetObjectByKey(objDetached.EntityKey, out original)) { objContext.ApplyCurrentValues(objDetached.EntityKey.EntitySetName, objDetached); } else { throw new ObjectNotFoundException(); } } }
public void Save(TEntity entity) { TEntity existing = LoadById(entity.ID); if (existing == null) { DbContext.Set <TEntity>().Add(entity); } else { string entitySetName = GetEntitySetName <TEntity>(); ObjectContext.ApplyCurrentValues(entitySetName, entity); } ObjectContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave); }
public void Update(T entity) { if (entity == null) { throw new ArgumentNullException("entity"); } if (!IsAttached(entity)) { objectSet.Attach(entity); } context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified); context.ApplyCurrentValues(entitySet.Name, entity); context.SaveChanges(); }
public bool PersistEntity <EntityType>(ObjectContext objCtx, string entitySetName, EntityType newEntity) where EntityType : class { bool isNew = false; object oldObject = null; objCtx.TryGetObjectByKey(objCtx.CreateEntityKey(entitySetName, newEntity), out oldObject); if (oldObject == null) { objCtx.AddObject(entitySetName, newEntity); isNew = true; } else { objCtx.ApplyCurrentValues(entitySetName, newEntity); } objCtx.DetectChanges(); objCtx.SaveChanges(); return(isNew); }
public static void AttachUpdated(this ObjectContext context, EntityObject detachedEntity) { #region EntityKey is null if (detachedEntity.EntityKey == null) { //String entitySetName = GetEntitySetFullName(context, detachedEntity); //int objectId = (int)detachedEntity.GetType().GetProperty("Id").GetValue(detachedEntity, null); ////detachedEntity.EntityKey = new System.Data.EntityKey(entitySetName, "Id", objectId); //detachedEntity.EntityKey = new EntityKey(context.GetEntitySetName(detachedEntity.GetType())); //// create a new primary key //Guid newPk = Guid.NewGuid(); //// create new entity key //EntityKey entityKey = new EntityKey(context.GetType().Name + "." + detachedEntity.ToString(), pkName, newPk); //// get type name of new entity //String typeName = oc.GetType().Namespace + "." + entityKey.EntitySetName; //// create a new entity } #endregion if (detachedEntity.EntityState == EntityState.Detached) { object currentEntity = null; if (context.TryGetObjectByKey(detachedEntity.EntityKey, out currentEntity)) { context.ApplyCurrentValues(detachedEntity.EntityKey.EntitySetName, detachedEntity); var newEntity = detachedEntity as IEntityWithRelationships; var oldEntity = currentEntity as IEntityWithRelationships; if (newEntity != null && oldEntity != null) { context.ApplyReferencePropertyChanges(newEntity, oldEntity); } } else { throw new ObjectNotFoundException(); } } }
/// <summary> /// Update the specified entity /// </summary> /// <param name="entity">Entity to update</param> public virtual void Update(T entityToUpdate) { //EntityKey key = GenerateKey(entityToUpdate); EntityKey key = GenerateKey_64Bit(entityToUpdate); var originalEntity = (T)_context.GetObjectByKey(key); string qualifiedEntitySetName = this.GetEntitySetName(typeof(T)); Type parentType = entityToUpdate.GetType(); this.SetInsertAuditInfo(entityToUpdate, originalEntity, parentType); _context.ApplyCurrentValues(qualifiedEntitySetName, entityToUpdate); //Retrive Audit info by reflection IUser/IDate //EntityKey key = GenerateKey(entityToUpdate); //var originalEntity = (T)_context.GetObjectByKey(key); //string qualifiedEntitySetName = this.GetEntitySetName(typeof(T)); //Type parentType = entityToUpdate.GetType(); //this.SetInsertAuditInfo(entityToUpdate, originalEntity, parentType); //////////////////////////////////////// // _objectSet.Attach(entityToUpdate); //_context.ObjectStateManager.ChangeObjectState(entityToUpdate, EntityState.Modified); }
/// <summary> /// Adds or attaches the entity to the context. If the entity has an EntityKey, /// the entity is attached, otherwise a clone of it is added. /// </summary> /// <returns>The attached entity.</returns> public static object AddOrAttachInstance(this ObjectContext context, object entity, bool applyPropertyChanges) { EntityKey entityKey = ((IEntityWithKey)entity).EntityKey; if (entityKey == null) { object attachedEntity = GetShallowEntityClone(entity); context.AddObject(context.GetEntitySetName(entity.GetType()), attachedEntity); ((IEntityWithKey)entity).EntityKey = ((IEntityWithKey)attachedEntity).EntityKey; return(attachedEntity); } else { object attachedEntity = context.GetObjectByKey(entityKey); if (applyPropertyChanges) { context.ApplyCurrentValues(entityKey.EntitySetName, entity); } return(attachedEntity); } }
/// <summary> /// Insert if new otherwise attach data into context /// </summary> /// <param name="entity"></param> public void AddOrAttach(E entity) { // Define an ObjectStateEntry and EntityKey for the current object. EntityKey key; object originalItem; // Get the detached object's entity key. if (((IEntityWithKey)entity).EntityKey == null) { // Get the entity key of the updated object. key = _ctx.CreateEntityKey(this.GetEntitySetName(entity.GetType().Name), entity); } else { key = ((IEntityWithKey)entity).EntityKey; } try { // Get the original item based on the entity key from the context // or from the database. if (_ctx.TryGetObjectByKey(key, out originalItem)) {//accept the changed property if (originalItem is EntityObject && ((EntityObject)originalItem).EntityState != EntityState.Added) { // Call the ApplyCurrentValues method to apply changes // from the updated item to the original version. _ctx.ApplyCurrentValues(key.EntitySetName, entity); } } else {//add the new entity Add(entity); }//end else } catch (Exception ex) { throw ex; } }
/// <summary> /// Agrega al contexto la entidad que le llega y le aplica las modificaciones que tiene con respecto al objeto que esta en el repositorio /// </summary> /// <param name="context">Contexto agregado a la entidad</param> /// <param name="objectDetached">Entidad a la que se le agrega el contexto</param> public static void AttachUpdated(this ObjectContext context, EntityObject objectDetached) { if (context == null) throw new Exception("context no puede ser null"); if (objectDetached == null) throw new Exception("objectDetached no puede ser null"); if ((objectDetached.EntityState == EntityState.Detached) || (objectDetached.EntityState == EntityState.Modified)) { object currentEntityInDb = null; if (context.TryGetObjectByKey(objectDetached.EntityKey, out currentEntityInDb)) { context.ApplyCurrentValues(objectDetached.EntityKey.EntitySetName, objectDetached); //(CDLTLL)Apply property changes to all referenced entities in context //context.ApplyReferencePropertyChanges((IEntityWithRelationships)objectDetached, (IEntityWithRelationships)currentEntityInDb); //Custom extensor method } else { throw new ObjectNotFoundException(); } } }