Beispiel #1
0
        private void UpdateChild(T originalEntity, Type parentType, ArrayList newChilds, Type Class, string childKey)
        {
            /*Get All Children from db */

            System.Reflection.PropertyInfo orginalChilds = parentType.GetProperty(Class.Name);
            Type   listType       = typeof(EntityCollection <>).MakeGenericType(new Type[] { Class });
            object oldDbChildList = Activator.CreateInstance(listType);

            oldDbChildList = orginalChilds.GetValue(originalEntity, null);
            /* *** */

            List <Int32>  oldIds       = new List <int>();
            List <Int32>  newIds       = new List <int>();
            List <object> oldChildList = new List <object>();

            foreach (var obj in (IEnumerable)oldDbChildList)
            {
                System.Reflection.PropertyInfo Id = Class.GetProperty(childKey);
                int value = Convert.ToInt32(Id.GetValue(obj, null));
                oldIds.Add(value);
                oldChildList.Add(obj);
            }

            foreach (var obj in newChilds.ToArray(Class))
            {
                System.Reflection.PropertyInfo Id = Class.GetProperty(childKey);
                int value = Convert.ToInt32(Id.GetValue(obj, null));
                newIds.Add(value);
                string qualifiedEntitySetName = this.GetEntitySetName(Class);
                if (oldIds.Contains(value))
                {
                    object childToUpdate = GetUpdatedChildWithAuditInfo(oldChildList, value, obj, childKey);
                    _context.ApplyCurrentValues(qualifiedEntitySetName, childToUpdate);
                }
                else
                {
                    _context.AddObject(qualifiedEntitySetName, obj);
                }
            }

            foreach (var old in oldChildList)
            {
                // Are there child items in the DB which are NOT in the
                // new child item collection anymore?
                System.Reflection.PropertyInfo Id = Class.GetProperty(childKey);
                int value = Convert.ToInt32(Id.GetValue(old, null));
                if (!newIds.Contains(value))
                {
                    // Yes -> It's a deleted child item -> Delete
                    _context.DeleteObject(old);
                }
            }
        }
        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++;
            }
        }
Beispiel #3
0
        /// <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);
        }
Beispiel #4
0
        /// <summary>
        /// Uses a reliable connection retry policy and transaction
        /// scoping to add and submit a set of EntityObjects.
        /// </summary>
        /// <typeparam name="T">Must derive from <typeparamref name="EntityObject"/>.</typeparam>
        /// <param name="context">Any ObjectContext</param>
        /// <param name="objects">A set of <typeparamref name="EntityObject"/>s to save.</param>
        public static void AddObjectsAndSave <T>(this ObjectContext context, IEnumerable <T> objects)
            where T : EntityObject
        {
            if (!objects.Any())
            {
                return;
            }

            var policy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>
                             (10, TimeSpan.FromSeconds(10));
            var tso = new TransactionOptions();

            tso.IsolationLevel = IsolationLevel.ReadCommitted;

            var name = context.GetTableName <T>();

            foreach (var item in objects)
            {
                context.AddObject(name, item);
            }


            policy.ExecuteAction(() =>
            {
                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, tso))
                {
                    context.SaveChanges();

                    ts.Complete();
                }
            });
        }
Beispiel #5
0
        public int Add(TElement item, bool isAddNew)
        {
            EnsureEntitySet();

            Debug.Assert(_objectContext != null, "ObjectContext is null.");

            // If called for AddNew operation, add item to binding list, pending addition to ObjectContext.
            if (!isAddNew)
            {
                _objectContext.AddObject(TypeHelpers.GetFullName(_entitySet.EntityContainer.Name, _entitySet.Name), item);
            }

            _bindingList.Add(item);

            return(_bindingList.Count - 1);
        }
 public void Guardar(ObjectContext contexto, SaveOptions saveOptions)
 {
     if (this.EntityKey == null)
     {
         contexto.AddObject(this.GetType().Name, this);
     }
     contexto.SaveChanges(saveOptions);
 }
Beispiel #7
0
 public void Add <TEntity>(TEntity entity) where TEntity : class
 {
     if (entity == null)
     {
         throw new ArgumentNullException("entity");
     }
     ObjectContext.AddObject(GetEntityName <TEntity>(), entity);
 }
 public void InsertEntities <EntityType>(ObjectContext objCtx, string entitySetName, IEnumerable <EntityType> newEntities) where EntityType : class
 {
     foreach (EntityType entity in newEntities)
     {
         objCtx.AddObject(entitySetName, entity);
     }
     objCtx.DetectChanges();
     objCtx.SaveChanges();
 }
Beispiel #9
0
        private TransactionLogEntry AddLogEntryToDatabase(ObjectContext ctx)
        {
            var transactionLogEntry = new TransactionLogEntry();

            ctx.AddObject("Entities.TransactionLog", transactionLogEntry);
            ctx.SaveChanges();

            return(transactionLogEntry);
        }
Beispiel #10
0
        public void Save(E entity)
        {
            String entitySetName = eContainerName + "." + eClass.Name;

            ctx.AddObject(entitySetName, entity);
            ctx.SaveChanges();
            ctx.Refresh(RefreshMode.StoreWins, entity);
            ctx.AcceptAllChanges();
        }
Beispiel #11
0
        //
        // original values
        //

        // Extension method for the ObjectContext which will create an object instance that is essentially equivalent
        // to the original object that was added or attached to the context before any changes were performed.
        // NOTE: This object will have no relationships--just the original value properties.
        public static object CreateOriginalValuesObject(this ObjectContext context, object source)
        {
            // Get the state entry of the source object
            //     NOTE: For now we require the object to implement IEntityWithKey.
            //           This is something we should be able to relax later.
            Debug.Assert(source is IEntityWithKey);
            EntityKey sourceKey = ((IEntityWithKey)source).EntityKey;
            // This method will throw if the key is null or an entry isn't found to match it.  We
            // could throw nicer exceptions, but this will catch the important invalid cases.
            ObjectStateEntry sourceStateEntry = context.ObjectStateManager.GetObjectStateEntry(sourceKey);

            // Return null for added entities & throw an exception for detached ones.  In other cases we can
            // always make a new object with the original values.
            switch (sourceStateEntry.State)
            {
            case EntityState.Added:
                return(null);

            case EntityState.Detached:
                throw new InvalidOperationException("Can't get original values when detached.");
            }

            // Create target object and add it to the context so that we can easily set properties using
            // the StateEntry.  Since objects in the added state use temp keys, we know this won't
            // conflict with anything already in the context.
            object target            = Activator.CreateInstance(source.GetType());
            string fullEntitySetName = sourceKey.EntityContainerName + "." + sourceKey.EntitySetName;

            context.AddObject(fullEntitySetName, target);
            EntityKey targetKey = context.CreateEntityKey(fullEntitySetName, target);

            ObjectStateEntry targetStateEntry = context.ObjectStateManager.GetObjectStateEntry(targetKey);

            // Copy original values from the sourceStateEntry to the targetStateEntry.  This will
            // cause the corresponding properties on the object to be set.
            for (int i = 0; i < sourceStateEntry.OriginalValues.FieldCount; i++)
            {
                // TODO: For best perf we should have a switch on the type here so that we could call
                // the type-specific methods and avoid boxing.
                targetStateEntry.CurrentValues.SetValue(i, sourceStateEntry.OriginalValues[i]);
            }

            // Detach the object we just created since we only attached it temporarily in order to use
            // the stateEntry.
            context.Detach(target);

            // Set the EntityKey property on the object (if it implements IEntityWithKey).
            IEntityWithKey targetWithKey = target as IEntityWithKey;

            if (targetWithKey != null)
            {
                targetWithKey.EntityKey = sourceKey;
            }

            return(target);
        }
Beispiel #12
0
        /// <summary>
        /// Связывает сущность Entity model с контекстом данных
        /// </summary>
        public static void AttachByIdValue <TEntity>(this ObjectContext context, TEntity rootEntity)
            where TEntity : class, IStoreEntity
        {
            context.AddObject(typeof(TEntity).Name, rootEntity);

            if (rootEntity.ID != 0)
            {
                context.ObjectStateManager.GetObjectStateEntry(rootEntity).SetModified();
            }
        }
Beispiel #13
0
 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);
     }
 }
Beispiel #14
0
        private ObjectStateEntry AddObjectStateEntry(EFEntityInfo entityInfo)
        {
            var ose = GetObjectStateEntry(entityInfo.Entity, false);

            if (ose != null)
            {
                return(ose);
            }
            ObjectContext.AddObject(entityInfo.EntitySetName, entityInfo.Entity);
            // Attach has lots of side effect - add has far fewer.
            return(GetObjectStateEntry(entityInfo));
        }
        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);
        }
Beispiel #16
0
        public void Create(E entity)
        {
            /* Adds the object to the object context. The entity's EntityState
             * will be set to Added. Therefore, when SaveChanges is called, it
             * will be clear to the Entity Framework that this entity needs to
             * be inserted into the database.
             */
            context.AddObject(GetQualifiedEntitySetName(entityClass.Name),
                              entity);

            /* Persists back to the database all of the changes made to
             * the entities. By default, the SaveChanges method calls the method
             * AcceptAllChanges after it has performed the database
             * modifications. AcceptAllChanges pushes the current values of
             * every attached entity into the original values and then changes
             * their EntityState to Unchanged.
             */
            context.SaveChanges();
        }
Beispiel #17
0
        public void AttachObject(EntityObject entity)
        {
            List <EntityObject> list = new List <EntityObject>();
            int maxLevel             = 2;
            int curLevel             = 0;

            AttachObjectRelation(entity, ref list, maxLevel, curLevel);

            EntityKey key = entity.EntityKey;

            if (key != null)
            {
                GetEntity(key);
                lbc.ApplyPropertyChanges(entity.GetType().Name, entity);
            }
            else
            {
                lbc.AddObject(entity.GetType().Name, entity);
            }

            //for (int i = 0;i < list.Count; i++)
            //{
            //    EntityObject curEntity = list[i];
            //    try
            //    {
            //        EntityKey key = curEntity.EntityKey;
            //        if (key != null)
            //        {
            //            GetEntity(key);
            //            lbc.ApplyPropertyChanges(curEntity.GetType().Name, entity);
            //        }
            //        else
            //        {
            //            lbc.AddObject(curEntity.GetType().Name, entity);
            //        }
            //    }
            //    catch (Exception ex)
            //    {

            //    }

            //}
        }
Beispiel #18
0
        public static int SaveChanges <TEntity>(this ObjectContext dbContext, IEnumerable <TEntity> bindingList, string targetDbSet)
        {
            int    count    = 0;
            string fullName = targetDbSet;

            System.Data.Entity.EntityState?state;
            foreach (var item in bindingList)
            {
                TEntity i = (TEntity)item;
                state = (System.Data.Entity.EntityState)i.GetType().GetProperty("EntityState").GetValue(i, null);
                if (state != null && state == System.Data.Entity.EntityState.Detached)
                {
                    dbContext.AddObject(fullName, i);
                }
            }

            count = dbContext.SaveChanges();
            return(count);
        }
        private void AddEntityHistories(ObjectContext ctx, EntityState state, HistoryActionType action)
        {
            IEnumerable <EntityWrapper> entities = this.Entities.Where(x => x.State == state);

            foreach (EntityWrapper entityWrapper in entities)
            {
                if ((entityWrapper.Entity is EntityObject) && (entityWrapper.Entity is IEntityExtend))
                {
                    CoreHistory coreHistory = HistoryManager.CreateCoreHistory((IEntityExtend)entityWrapper.Entity, action, null, null);
                    if (entityWrapper.Entity is IWithHistory)
                    {
                        IList <IHistory> histories = ((IWithHistory)entityWrapper.Entity).CreateHistoryEntities(coreHistory);
                        foreach (IHistory history in histories)
                        {
                            this.GetHistoryEntities(entityWrapper.Key).Add(history);
                            ctx.AddObject(history.EntitySetName, history);
                        }
                    }
                }
            }
        }
Beispiel #20
0
        /// <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);
            }
        }
        public static void AddExternalIdMapping(ObjectContext context, EventOccurrenceV2 source, EventOccurrence target)
        {
            if (!string.IsNullOrEmpty(source.OccurrenceExternalId))
            {
                var mappingExists = context.CreateObjectSet<DataImportEntityIdMap>()
                    .Any(m => m.EntityName == "EventOccurrence" &&
                    m.InternalId == target.Id &&
                    m.ExternalId == source.OccurrenceExternalId);

                if (!mappingExists)
                {
                    context.AddObject("DataImportEntityIdMaps", new DataImportEntityIdMap
                    {
                        EntityName = "EventOccurrence",
                        DataImportId = 2,
                        InternalId = target.Id,
                        ExternalId = source.OccurrenceExternalId
                    });
                    context.SaveChanges();
                }
            }
        }
Beispiel #22
0
        public static void AddExternalIdMapping(ObjectContext context, EventV2 source, Event theEvent)
        {
            if (!string.IsNullOrEmpty(source.EventExternalId))
            {
                var existingMappings = context.CreateObjectSet<DataImportEntityIdMap>()
                    .Where(m => m.EntityName == "Event" && m.InternalId == theEvent.Id)
                    .ToList();

                if (existingMappings.Count == 1)
                {
                    if (existingMappings[0].ExternalId != source.EventExternalId)
                    {
                        // Update ExternalId on existing mapping
                        existingMappings[0].ExternalId = source.EventExternalId;
                    }
                }
                else
                {
                    // Remove ambiguous mappings (if any)
                    if (existingMappings.Count > 1)
                    {
                        foreach (var mapping in existingMappings)
                        {
                            context.DeleteObject(mapping);
                        }
                    }

                    // Create new mapping
                    context.AddObject("DataImportEntityIdMaps", new DataImportEntityIdMap
                    {
                        EntityName = "Event",
                        DataImportId = 2,
                        InternalId = theEvent.Id,
                        ExternalId = source.EventExternalId
                    });
                }
            }
        }
Beispiel #23
0
        public static void AddObjectsAndSaveWithIdentityInsert <T>(
            this ObjectContext context, IEnumerable <T> objects)
            where T : EntityObject
        {
            if (!objects.Any())
            {
                return;
            }

            Action <IEnumerable <T> > exec = (obj) =>
            {
                var policy = new RetryPolicy <SqlAzureTransientErrorDetectionStrategy>
                                 (10, TimeSpan.FromSeconds(10));

                var name = context.GetTableName <T>();

                foreach (var item in obj)
                {
                    context.AddObject(name, item);
                }

                policy.ExecuteAction(() =>
                {
                    context.Connection.Open();
                    var trans = context.Connection.BeginTransaction();

                    context.ExecuteStoreCommand("SET IDENTITY_INSERT " + context.GetTableName <T>() + " ON");
                    context.SaveChanges();
                    context.ExecuteStoreCommand("SET IDENTITY_INSERT " + context.GetTableName <T>() + " OFF");

                    trans.Commit();
                    context.AcceptAllChanges();
                    context.Connection.Close();
                });
            };

            context.AddObjectsAndSave(objects, doThisInstead: exec);
        }
Beispiel #24
0
 public void Insert <T>(ObjectContext context, T entity, out OperationResult operationResult) where T : class, new()
 {
     try
     {
         using (context)
         {
             //context.GetTable<T>().InsertOnSubmit(entity);
             context.AddObject(typeof(T).Name, entity);
             context.SaveChanges();
             operationResult = new OperationResult()
             {
                 Type = OperationResult.ResultType.Success
             };
         }
     }
     catch (Exception ex)
     {
         operationResult = new OperationResult()
         {
             Type = OperationResult.ResultType.Failure, Message = ex.StackTrace
         };
     }
 }
Beispiel #25
0
        private static void InternalAttach(ObjectContext ctx, object entity, bool addToContext, string entitySetName, List <object> analyzedEntities)
        {
            var objectType   = ObjectContext.GetObjectType(entity.GetType());
            var associations = ctx.MetadataWorkspace.GetItems <AssociationType>(DataSpace.OSpace);
            var os           = ctx.MetadataWorkspace.GetItem <EntityType>(objectType.FullName, DataSpace.OSpace);
            var item         = (EntityType)ctx.MetadataWorkspace.GetEdmSpaceType(os);
            var value        = ((XElement)(item.KeyMembers[0].MetadataProperties.First(p => p.Name == "http://EF:InsertWhen").Value)).Value;
            var idType       = ((PrimitiveType)item.Members[item.KeyMembers[0].Name].TypeUsage.EdmType).ClrEquivalentType;
            var id           = entity.GetType().GetProperty(item.KeyMembers[0].Name).GetValue(entity, null);

            if (id.Equals(Convert.ChangeType(value, idType)))
            {
                if (addToContext)
                {
                    ctx.AddObject(entitySetName, entity);
                }
                foreach (var association in ctx.MetadataWorkspace.GetItems <AssociationType>(DataSpace.CSpace).Where(a => a.AssociationEndMembers[1].Name == objectType.Name))
                {
                    var propName               = association.ReferentialConstraints[0].ToProperties[0].Name;
                    var foreignKey             = entity.GetType().GetProperty(propName).GetValue(entity, null);
                    var principalEntity        = association.AssociationEndMembers[0].GetEntityType();
                    var principalIdInsertValue = ((XElement)(principalEntity.KeyMembers[0].MetadataProperties.First(p => p.Name == "http://EF:InsertWhen").Value)).Value;
                    var principalIdType        = ((PrimitiveType)principalEntity.Members[principalEntity.KeyMembers[0].Name].TypeUsage.EdmType).ClrEquivalentType;
                    var navPropName            = item.NavigationProperties.First(p => p.RelationshipType.FullName == association.FullName).Name;
                    var navObject              = entity.GetType().GetProperty(navPropName).GetValue(entity, null);
                    if (!foreignKey.Equals(Convert.ChangeType(principalIdInsertValue, idType)))
                    {
                        ctx.ObjectStateManager.GetObjectStateEntry(navObject).ChangeState(EntityState.Unchanged);
                    }
                }
            }
            else
            if (addToContext)
            {
                ctx.AttachTo(entitySetName, entity);
            }
        }
Beispiel #26
0
        protected override void InsertItem(int index, T item)
        {
            base.InsertItem(index, item);

            objectContext.AddObject(entitySetName, item);
        }
        /// <summary>
        /// Apply changes from the newEntity to the original entity
        /// </summary>
        /// <param name="objectContext">ObjectContext instance.</param>
        /// <param name="originalTrackedEntity">original entity which is tracked by the context.</param>
        /// <param name="newEntity">newEntity which contains all the changed values.</param>
        private static void ApplyChangesToEntity(ObjectContext objectContext, object originalTrackedEntity, object newEntity)
        {
            ObjectStateEntry objectStateEntry = objectContext.ObjectStateManager.GetObjectStateEntry(originalTrackedEntity);
            string entitySetName = ObjectContextServiceProvider.GetEntitySetName(objectStateEntry, objectContext.DefaultContainerName);
            if (objectStateEntry.State == EntityState.Added)
            {
                // In the case of batching if we do a PUT after POST in the same changeset, we need to detach and re-add.
                objectContext.Detach(originalTrackedEntity);
                objectContext.AddObject(entitySetName, newEntity);
            }
            else
            {
#pragma warning disable 618
                // Since we use to do this in V1, keeping the same code there.
                // Apply property changes as specified in the new object.
                objectContext.ApplyPropertyChanges(entitySetName, newEntity);
#pragma warning restore 618
            }
        }
 public void PersistCreationOf(IAggregateRoot entity)
 {
     _objectContext.AddObject(GetEntitySetName(), entity);
 }
Beispiel #29
0
 public void Create(T entity)
 {
     objectContext.AddObject(entitySetName, entity);
 }
 public void InsertEntity <EntityType>(ObjectContext objCtx, string entitySetName, EntityType newEntity) where EntityType : class
 {
     objCtx.AddObject(entitySetName, newEntity);
     objCtx.SaveChanges();
 }
Beispiel #31
0
    public static void GenerarHojadeRuta(ObjectContext pContext, DateTime FInicio, DateTime FFin, Entidades.ContratoEmpresas pContratoEmpresas)
    {
        string queryString = @"SELECT VALUE CabeceraHojasDeRuta FROM 
            EntidadesConosud.CabeceraHojasDeRuta AS CabeceraHojasDeRuta";
        ObjectQuery <Entidades.CabeceraHojasDeRuta> CabeceraHojasDeRutaQuery1 =
            new ObjectQuery <Entidades.CabeceraHojasDeRuta>(queryString, pContext);

        DateTime FechaInicio = FInicio;
        DateTime FechaFinal  = FFin;

        int ultimonrocarpeta = 1;

        try
        {
            ultimonrocarpeta  = CabeceraHojasDeRutaQuery1.Max(c => c.NroCarpeta);
            ultimonrocarpeta += 1;
        }
        catch { }


        long id = Convert.ToInt64(Helpers.EstadosHoja.NoAprobada);
        IEnumerable <KeyValuePair <string, object> > entityKeyValues = new KeyValuePair <string, object>[] {
            new KeyValuePair <string, object>("IdClasificacion", id)
        };
        EntityKey key = new EntityKey("EntidadesConosud.Clasificacion", entityKeyValues);

        Entidades.Clasificacion _est = (Entidades.Clasificacion)pContext.GetObjectByKey(key);

        /// Guardo la ultima cabecera antes de generar las nuevas para
        /// luego obtener los legados de la mism.

        Entidades.CabeceraHojasDeRuta UltimaCabecera = null;
        if (pContratoEmpresas.IdContratoEmpresas > 0)
        {
            if (!pContratoEmpresas.CabeceraHojasDeRuta.IsLoaded)
            {
                pContratoEmpresas.CabeceraHojasDeRuta.Load();
            }
            UltimaCabecera = pContratoEmpresas.CabeceraHojasDeRuta.OrderBy(w => w.Periodo).Last();
        }


        while (GeneraxFecha(ref FechaInicio, ref FechaFinal))
        {
            if (UltimaCabecera == null || !(UltimaCabecera.Periodo.Month == FechaFinal.Month && UltimaCabecera.Periodo.Year == FechaFinal.Year))
            {
                /// control por las dudas que el primer periodo que se intenta crear ya existe.
                if (UltimaCabecera == null || string.Format("{0:MMyyyy}", FechaInicio) != string.Format("{0:MMyyyy}", UltimaCabecera.Periodo))
                {
                    /// controlo que el periodo que se esta intentando crear no exista ya.
                    if (!pContratoEmpresas.CabeceraHojasDeRuta.Any(w => string.Format("{0:MMyyyy}", w.Periodo) == string.Format("{0:MMyyyy}", FechaInicio)))
                    {
                        /// Genero la cabecera de hoja de ruta
                        Entidades.CabeceraHojasDeRuta _CabHojaRuta = new Entidades.CabeceraHojasDeRuta();
                        _CabHojaRuta.ContratoEmpresas = pContratoEmpresas;
                        _CabHojaRuta.Estado           = _est;
                        _CabHojaRuta.Periodo          = FechaInicio;
                        _CabHojaRuta.NroCarpeta       = ultimonrocarpeta;
                        _CabHojaRuta.Estimacion       = string.Empty;
                        _CabHojaRuta.EsFueraTermino   = false;
                        pContext.AddObject("EntidadesConosud.CabeceraHojasDeRuta", _CabHojaRuta);

                        queryString = @"SELECT VALUE Plantilla FROM EntidadesConosud.Plantilla AS Plantilla";

                        ObjectQuery <Entidades.Plantilla> PlantillaQuery1 =
                            new ObjectQuery <Entidades.Plantilla>(queryString, pContext);

                        /// Genero los items de las hojas de ruta
                        foreach (Entidades.Plantilla plan in PlantillaQuery1.Select(p => p))
                        {
                            Entidades.HojasDeRuta _HojasDeRuta = new Entidades.HojasDeRuta();
                            _HojasDeRuta.Plantilla      = plan;
                            _HojasDeRuta.HojaAprobado   = false;
                            _HojasDeRuta.HojaComentario = string.Empty;
                            _HojasDeRuta.AuditadoPor    = string.Empty;
                            _HojasDeRuta.DocComentario  = string.Empty;
                            _CabHojaRuta.HojasDeRuta.Add(_HojasDeRuta);

                            pContext.AddObject("EntidadesConosud.HojasDeRuta", _HojasDeRuta);
                        }

                        /// Asocio  los legajos a la nueva cabecera

                        if (UltimaCabecera != null)
                        {
                            if (!UltimaCabecera.ContEmpLegajos.IsLoaded)
                            {
                                UltimaCabecera.ContEmpLegajos.Load();
                            }
                            foreach (Entidades.ContEmpLegajos itemContLeg in UltimaCabecera.ContEmpLegajos)
                            {
                                if (!itemContLeg.LegajosReference.IsLoaded)
                                {
                                    itemContLeg.LegajosReference.Load();
                                }

                                Entidades.ContEmpLegajos newContLeg = new Entidades.ContEmpLegajos();
                                newContLeg.ContratoEmpresas = pContratoEmpresas;
                                newContLeg.Legajos          = itemContLeg.Legajos;
                                _CabHojaRuta.ContEmpLegajos.Add(newContLeg);

                                pContext.AddObject("EntidadesConosud.ContEmpLegajos", newContLeg);
                            }
                        }
                    }
                }
            }

            FechaInicio       = FechaInicio.AddMonths(1);
            ultimonrocarpeta += 1;
        }
    }
Beispiel #32
0
 /// <summary>
 /// Insert new data into context
 /// </summary>
 /// <typeparam name="E"></typeparam>
 /// <param name="entity"></param>
 public void Add(TEntity entity)
 {
     //_ctx.AddObject(entity.GetType().Name, entity);
     _ctx.AddObject(GetEntitySetName(_ctx), entity);
 }
Beispiel #33
0
        private static DiscountCode CreateEventDiscountCode(ObjectContext context, DiscountCodeDtoV2 code)
        {
            int discountTypeId = LookupDiscountType(context, code.DiscountType);

            var discountCode = new DiscountCode
            {
                Code = code.Code,
                Description = code.Description,
                DiscountTypeId = discountTypeId,
                DiscountValue = Convert.ToDecimal(code.DiscountValue, CultureInfo.InvariantCulture),
                StartDate = string.IsNullOrEmpty(code.StartDate) ? new DateTime?() : DateTime.Parse(code.StartDate, CultureInfo.InvariantCulture),
                EndDate = string.IsNullOrEmpty(code.StartDate) ? new DateTime?() : DateTime.Parse(code.EndDate, CultureInfo.InvariantCulture),
                IsEnabled = bool.Parse(code.IsEnabled),
                IsGroupCode = bool.Parse(code.IsGroupCode),
                IsFromOrgUnit = false,
                RequiredGroupSize = int.Parse(code.RequiredGroupSize, CultureInfo.InvariantCulture),
            };

            context.AddObject("DiscountCodes", discountCode);

            return discountCode;
        }
        public static EventOccurrence BuildNewOccurrence(ObjectContext objectContext, int newEventId, EventOccurrence item)
        {
            var newOccurrence = new EventOccurrence
            {
                ContactName = item.ContactName,
                ContactEmail = item.ContactEmail,
                ContactPhone = item.ContactPhone,
                ContactPhoneExtension = item.ContactPhoneExtension,
                Cost = item.Cost,
                CostCenter = item.CostCenter,
                OrgUnitId = item.OrgUnitId,
                MaximumAttendees = item.MaximumAttendees,
                LastUpdated = System.DateTime.UtcNow,
                PaymentProcessorConfigurationId = item.PaymentProcessorConfigurationId,
                IsRegistrationEnabled = item.IsRegistrationEnabled,
                IsNotificationListEnabled = item.IsNotificationListEnabled,
                IsNotifyContactEnabled = item.IsNotifyContactEnabled,
                SpecialInstructions = item.SpecialInstructions,
                LocationOrgUnitId = item.LocationOrgUnitId,
                LocationName = item.LocationName,
                Address1 = item.Address1,
                Address2 = item.Address2,
                City = item.City,
                PostalCode = item.PostalCode,
                StateId = item.StateId,
                CountryId = item.CountryId,
                Latitude = item.Latitude,
                Longitude = item.Longitude,
                IsGuestDemographicInfoRequired = item.IsGuestDemographicInfoRequired
            };

            newOccurrence.SetPresenter(item.Presenter);
            newOccurrence.SetIsEnabled(item.IsEnabled);
            newOccurrence.SetEventId(newEventId);

            newOccurrence.SetAddress1(item.Address1);
            newOccurrence.SetAddress2(item.Address2);

            newOccurrence.SetRegistrationDates(item.RegistrationStartDate, item.RegistrationEndDate);

            if (item.IsPriceScheduleEnabled)
                newOccurrence.EnablePricingSchedule();
            else
                newOccurrence.DisablePricingSchedule();

            CaptureCostScheduleData(item, newOccurrence);

            objectContext.AddObject("EventOccurrences", newOccurrence);
            objectContext.SaveChanges();

            //event occurrence documents
            foreach (var doc in item.EventOccurrencesDocuments)
            {
                var newDoc = new EventOccurrencesDocument()
                {
                    DocumentPath = doc.DocumentPath,
                    EventOccurrence = newOccurrence
                };
                newOccurrence.EventOccurrencesDocuments.Add(newDoc);
            }

            //event occurrence dates
            foreach (var dateItem in item.EventOccurrenceDates)
            {
                newOccurrence.AddOccurrenceDate(dateItem.StartDate, dateItem.EndDate);
            }
            objectContext.SaveChanges();

            return newOccurrence;
        }
 /// <summary>
 /// Adds the given entity to the context.
 /// </summary>
 public static void AddObject(this ObjectContext context, object entity)
 {
     context.AddObject(context.GetEntitySetName(entity.GetType()), entity);
 }