示例#1
0
文件: Group.cs 项目: philltran/Rock
        /// <summary>
        /// Pres the save changes.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="state">The state.</param>
        public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.EntityState state)
        {
            if (state == System.Data.Entity.EntityState.Deleted)
            {
                // manually delete any grouprequirements of this group since it can't be cascade deleted
                var groupRequirementService = new GroupRequirementService(dbContext as RockContext);
                var groupRequirements       = groupRequirementService.Queryable().Where(a => a.GroupId.HasValue && a.GroupId == this.Id).ToList();
                if (groupRequirements.Any())
                {
                    groupRequirementService.DeleteRange(groupRequirements);
                }

                // manually set any attendance search group ids to null
                var attendanceService = new AttendanceService(dbContext as RockContext);
                foreach (var attendance in attendanceService.Queryable()
                         .Where(a =>
                                a.SearchResultGroupId.HasValue &&
                                a.SearchResultGroupId.Value == this.Id))
                {
                    attendance.SearchResultGroupId = null;
                }
            }

            base.PreSaveChanges(dbContext, state);
        }
示例#2
0
        /// <summary>
        /// Method that will be called on an entity immediately before the item is saved by context
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="state">The state.</param>
        public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.EntityState state)
        {
            if (_logEntries != null)
            {
                if (_logEntries.Any())
                {
                    if (dbContext is RockContext)
                    {
                        var workflowLogService = new WorkflowLogService((dbContext as RockContext));
                        foreach (var logEntry in _logEntries)
                        {
                            workflowLogService.Add(new WorkflowLog {
                                LogDateTime = logEntry.LogDateTime, LogText = logEntry.LogText, WorkflowId = this.Id
                            });
                        }

                        _logEntries.Clear();
                    }
                }
            }

            // Set the workflow number
            if (state == System.Data.Entity.EntityState.Added)
            {
                int maxNumber = new WorkflowService(dbContext as RockContext)
                                .Queryable().AsNoTracking()
                                .Where(w => w.WorkflowTypeId == this.WorkflowTypeId)
                                .Max(w => (int?)w.WorkflowIdNumber) ?? 0;
                this.WorkflowIdNumber = maxNumber + 1;
            }

            base.PreSaveChanges(dbContext, state);
        }
示例#3
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext)
        {
            AttributeCache cacheAttribute = AttributeCache.Get(this.AttributeId, dbContext as RockContext);

            if (cacheAttribute == null)
            {
                return;
            }

            if (this.EntityId.HasValue && cacheAttribute.EntityTypeId.HasValue)
            {
                EntityTypeCache entityType = EntityTypeCache.Get(cacheAttribute.EntityTypeId.Value, dbContext as RockContext);

                if (entityType?.HasEntityCache() == true)
                {
                    entityType.FlushCachedItem(this.EntityId.Value);
                }
                else if (cacheAttribute.EntityTypeId == EntityTypeCache.GetId <Rock.Model.Device>())
                {
                    Rock.CheckIn.KioskDevice.FlushItem(this.EntityId.Value);
                }
            }

            if ((!cacheAttribute.EntityTypeId.HasValue || cacheAttribute.EntityTypeId.Value == 0) && string.IsNullOrEmpty(cacheAttribute.EntityTypeQualifierColumn) && string.IsNullOrEmpty(cacheAttribute.EntityTypeQualifierValue))
            {
                // Update GlobalAttributes if one of the values changed
                GlobalAttributesCache.Remove();
            }
        }
示例#4
0
        /// <summary>
        /// Creates a new PmnTaskChangeLog item.
        /// </summary>
        /// <param name="task">The task to create the log item for.</param>
        /// <param name="objState">The current state of the object.</param>
        /// <param name="identity">The current identity.</param>
        /// <param name="db">The datacontext.</param>
        /// <returns></returns>
        public async Task <Audit.PmnTaskChangeLog> CreateLogItemAsync(PmnTask task, System.Data.Entity.EntityState objState, ApiIdentity identity, DataContext db)
        {
            Audit.PmnTaskChangeLog logItem = null;
            if (identity != null)
            {
                var orgUser = await db.Users.Where(u => u.ID == identity.ID).Select(u => new { u.UserName, u.Organization.Acronym }).FirstOrDefaultAsync();

                logItem = new Audit.PmnTaskChangeLog
                {
                    Description = string.Format("Task has been {0} by {1}.", objState, (orgUser.Acronym + @"\" + orgUser.UserName)),
                    Reason      = objState,
                    UserID      = identity == null ? Guid.Empty : identity.ID,
                    TaskID      = task.ID,
                    Task        = task
                };
            }
            else
            {
                logItem = new Audit.PmnTaskChangeLog
                {
                    Description = string.Format("Task has been {0} because {1}.", objState, (task.Subject)),
                    Reason      = objState,
                    UserID      = Guid.Empty,
                    TaskID      = task.ID,
                    Task        = task
                };
            }

            return(logItem);
        }
示例#5
0
文件: Block.cs 项目: ewin66/rockrms
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext)
        {
            BlockCache.UpdateCachedEntity(this.Id, entityState);

            var model = this;

            if (model.SiteId.HasValue && model.SiteId != originalSiteId)
            {
                PageCache.RemoveSiteBlocks(model.SiteId.Value);
            }
            else if (model.LayoutId.HasValue && model.LayoutId != originalLayoutId)
            {
                PageCache.RemoveLayoutBlocks(model.LayoutId.Value);
            }

            if (originalSiteId.HasValue)
            {
                PageCache.RemoveSiteBlocks(originalSiteId.Value);
            }
            else if (originalLayoutId.HasValue)
            {
                PageCache.RemoveLayoutBlocks(originalLayoutId.Value);
            }
            else if (originalPageId.HasValue)
            {
                var page = PageCache.Get(originalPageId.Value);
                page.RemoveBlocks();
            }
        }
示例#6
0
        /// <summary>
        /// Prepare list of Audit Logs from data properties after modify  only
        /// </summary>
        /// <param name="dbEntry"></param>
        /// <param name="userId"></param>
        /// <param name="changeTime"></param>
        /// <param name="tableName"></param>
        /// <param name="keyName"></param>
        /// <param name="StatusPropertyId"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public List <AuditEntity> ModifiedAuditFromDataProperties(DbEntityEntry dbEntry, long userId, DateTime changeTime,
                                                                  string tableName, string primaryKeyName, string isActivePropertyId, string isDeletedProperty,
                                                                  System.Data.Entity.EntityState state)
        {
            List <AuditEntity> auditTrailsList = new List <AuditEntity>();

            //in case Modify entiry
            if (state == System.Data.Entity.EntityState.Modified)
            {
                // For Modified, add the changed record only , the current state of the entity , and the original
                var xml = GetModified(dbEntry, userId, changeTime, tableName, primaryKeyName, isActivePropertyId, isDeletedProperty);
                if (string.IsNullOrEmpty(xml))
                {
                    return(null);
                }
                auditTrailsList.Add(new AuditEntity()
                {
                    UserId    = userId,
                    LogDate   = changeTime,
                    EventType = "Modify",
                    TableName = tableName,
                    RecordId  = dbEntry.OriginalValues.GetValue <object>(primaryKeyName).ToString(),
                    ChangeXml = xml,
                    IsData    = true
                });
            }
            return(auditTrailsList);
        }
 /// <summary>
 /// 注册一个新的对象到仓储上下文中
 /// </summary>
 /// <typeparam name="TEntity"> 要注册的类型 </typeparam>
 public void RegisterNew <TEntity>(TEntity entity) where TEntity : class //EntityBase<TKey>
 {
     System.Data.Entity.EntityState state = Context.Entry(entity).State;
     if (state == System.Data.Entity.EntityState.Detached)
     {
         Context.Entry(entity).State = System.Data.Entity.EntityState.Added;
     }
     IsCommitted = false;
 }
        /// <summary>
        ///     注册一个新的对象到仓储上下文中
        /// </summary>
        /// <typeparam name="TEntity"> 要注册的类型 </typeparam>
        /// <typeparam name="TKey">实体主键类型</typeparam>
        /// <param name="entity"> 要注册的对象 </param>
        public void RegisterNew <TEntity, TKey>(TEntity entity) where TEntity : EntityBase <TKey>
        {
            EntityState state = Context.Entry(entity).State;

            if (state == EntityState.Detached)
            {
                Context.Entry(entity).State = EntityState.Added;
            }
            IsCommitted = false;
        }
示例#9
0
        public void ChangeState <TEntity>(TEntity entity, System.Data.Entity.EntityState requestedState) where TEntity : BaseEntity
        {
            var entry = this.Entry(entity);

            if (entry.State != requestedState)
            {
                // Only change state when requested state differs,
                // because EF internally sets all properties to modified
                // if necessary, even when requested state equals current state.
                entry.State = requestedState;
            }
        }
示例#10
0
        /// <summary>
        /// Pres the save.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="state">The state.</param>
        public override void PreSaveChanges(Data.DbContext dbContext, System.Data.Entity.EntityState state)
        {
            var channel = this.ContentChannel;

            if (state == System.Data.Entity.EntityState.Deleted)
            {
                ChildItems.Clear();
                ParentItems.Clear();
            }

            base.PreSaveChanges(dbContext, state);
        }
示例#11
0
        public void ChangeState <TEntity>(TEntity entity, EfState requestedState) where TEntity : BaseEntity
        {
            //Console.WriteLine("ChangeState ORIGINAL");
            var entry = this.Entry(entity);

            if (entry.State != requestedState)
            {
                // Only change state when requested state differs,
                // because EF internally sets all properties to modified
                // if necessary, even when requested state equals current state.
                entry.State = requestedState;
            }
        }
示例#12
0
 /// <summary>
 /// Pres the save changes.
 /// </summary>
 /// <param name="dbContext">The database context.</param>
 /// <param name="state">The state.</param>
 public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.EntityState state)
 {
     if (state == System.Data.Entity.EntityState.Deleted)
     {
         // manually delete any grouprequirements of this group since it can't be cascade deleted
         var groupRequirementService = new GroupRequirementService(dbContext as RockContext);
         var groupRequirements       = groupRequirementService.Queryable().Where(a => a.GroupId == this.Id).ToList();
         if (groupRequirements.Any())
         {
             groupRequirementService.DeleteRange(groupRequirements);
         }
     }
 }
示例#13
0
        /// <summary>
        /// Pres the save changes.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="state">The state.</param>
        public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.EntityState state)
        {
            if (ImageId.HasValue)
            {
                BinaryFileService binaryFileService = new BinaryFileService((RockContext)dbContext);
                var binaryFile = binaryFileService.Get(ImageId.Value);
                if (binaryFile != null && binaryFile.IsTemporary)
                {
                    binaryFile.IsTemporary = false;
                }
            }

            base.PreSaveChanges(dbContext, state);
        }
示例#14
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext)
        {
            var group = this.Group ?? new GroupService(new RockContext()).GetNoTracking(this.GroupId);

            if (group != null)
            {
                var groupType = GroupTypeCache.Get(group.GroupTypeId, (RockContext)dbContext);
                if (group.IsSecurityRole || groupType?.Guid == Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid())
                {
                    RoleCache.FlushItem(group.Id);
                    Rock.Security.Authorization.Clear();
                }
            }
        }
示例#15
0
文件: Site.cs 项目: ewin66/rockrms
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext)
        {
            SiteCache.UpdateCachedEntity(this.Id, entityState);

            using (var rockContext = new RockContext())
            {
                foreach (int pageId in new PageService(rockContext).GetBySiteId(this.Id)
                         .Select(p => p.Id)
                         .ToList())
                {
                    PageCache.UpdateCachedEntity(pageId, EntityState.Detached);
                }
            }
        }
示例#16
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext)
        {
            // Make sure CampusCache.All is cached using the dbContext (to avoid deadlock if snapshot isolation is disabled)
            var campusId = this.GetCampusId(dbContext as RockContext);

            // CampusCache has a CampusLocation that could get stale when Location changes, so refresh the CampusCache for this location's Campus
            if (this.CampusId.HasValue)
            {
                CampusCache.UpdateCachedEntity(this.CampusId.Value, EntityState.Detached);
            }

            // and also refresh the CampusCache for any Campus that uses this location
            foreach (var campus in CampusCache.All(dbContext as RockContext).Where(c => c.LocationId == this.Id))
            {
                CampusCache.UpdateCachedEntity(campus.Id, EntityState.Detached);
            }
        }
示例#17
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(System.Data.Entity.EntityState entityState, Rock.Data.DbContext dbContext)
        {
            // If the group changed, and it was a security group, flush the security for the group
            Guid?originalGroupTypeGuid = null;
            Guid groupTypeScheduleRole = Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid();

            if (_originalGroupTypeId.HasValue && _originalGroupTypeId != this.GroupTypeId)
            {
                originalGroupTypeGuid = GroupTypeCache.Get(_originalGroupTypeId.Value, (RockContext)dbContext)?.Guid;
            }

            var groupTypeGuid = GroupTypeCache.Get(this.GroupTypeId, (RockContext)dbContext)?.Guid;

            if (this.IsSecurityRole || (_originalIsSecurityRole == true) || (groupTypeGuid == groupTypeScheduleRole) || (originalGroupTypeGuid == groupTypeScheduleRole))
            {
                RoleCache.FlushItem(this.Id);
            }
        }
示例#18
0
文件: GroupType.cs 项目: sjison/Rock
        /// <summary>
        /// Pres the save.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="state">The state.</param>
        public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.EntityState state)
        {
            if (state == System.Data.Entity.EntityState.Deleted)
            {
                ChildGroupTypes.Clear();

                // manually delete any grouprequirements of this grouptype since it can't be cascade deleted
                var groupRequirementService = new GroupRequirementService(dbContext as RockContext);
                var groupRequirements       = groupRequirementService.Queryable().Where(a => a.GroupTypeId.HasValue && a.GroupTypeId == this.Id).ToList();
                if (groupRequirements.Any())
                {
                    groupRequirementService.DeleteRange(groupRequirements);
                }
            }

            // clean up the index
            if (state == System.Data.Entity.EntityState.Deleted && IsIndexEnabled)
            {
                this.DeleteIndexedDocumentsByGroupType(this.Id);
            }
            else if (state == System.Data.Entity.EntityState.Modified)
            {
                // check if indexing is enabled
                var changeEntry = dbContext.ChangeTracker.Entries <GroupType>().Where(a => a.Entity == this).FirstOrDefault();
                if (changeEntry != null)
                {
                    var originalIndexState = (bool)changeEntry.OriginalValues["IsIndexEnabled"];

                    if (originalIndexState == true && IsIndexEnabled == false)
                    {
                        // clear out index items
                        this.DeleteIndexedDocumentsByGroupType(Id);
                    }
                    else if (IsIndexEnabled == true)
                    {
                        // if indexing is enabled then bulk index - needed as an attribute could have changed from IsIndexed
                        BulkIndexDocumentsByGroupType(Id);
                    }
                }
            }

            base.PreSaveChanges(dbContext, state);
        }
示例#19
0
        public virtual void Update(T entity)
        {
            if (entity == null)
            {
                throw (new System.ArgumentNullException("entity"));
            }

            // **************************************************
            // Just For Debug!
            // **************************************************
            System.Data.Entity.EntityState oEntityState =
                DatabaseContext.Entry(entity).State;
            // **************************************************
            // /Just For Debug!
            // **************************************************

            if (oEntityState == System.Data.Entity.EntityState.Detached)
            {
                DbSet.Attach(entity);
            }

            // **************************************************
            // Just For Debug!
            // **************************************************
            oEntityState =
                DatabaseContext.Entry(entity).State;
            // **************************************************
            // /Just For Debug!
            // **************************************************

            DatabaseContext.Entry(entity).State =
                System.Data.Entity.EntityState.Modified;

            // **************************************************
            // Just For Debug!
            // **************************************************
            oEntityState =
                DatabaseContext.Entry(entity).State;
            // **************************************************
            // /Just For Debug!
            // **************************************************
        }
示例#20
0
        /// <summary>
        /// Removes or invalidates the CachedItem based on EntityState
        /// </summary>
        /// <param name="entityId">The entity identifier.</param>
        /// <param name="entityState">State of the entity. If unknown, use <see cref="EntityState.Detached" /></param>
        public static void UpdateCachedEntity(int entityId, System.Data.Entity.EntityState entityState)
        {
            // NOTE: Don't read the Item into the Cache here since it could be part of a transaction that could be rolled back.
            // Reading it from the database here could also cause a deadlock depending on the database isolation level.
            // Just remove it from Cache, and update the AllIds based on entityState

            if (entityState == EntityState.Deleted)
            {
                Remove(entityId);
            }
            else if (entityState == EntityState.Added)
            {
                // add this entity to All Ids, but don't fetch it into cache until somebody asks for it
                AddToAllIds(entityId);
            }
            else
            {
                FlushItem(entityId);
            }
        }
示例#21
0
        public static Axerrio.Data.Entity.EntityState ConvertFromEFEntityState(this System.Data.Entity.EntityState state, Axerrio.Data.Entity.EntityState currentState)
        {
            switch (state)
            {
            case System.Data.Entity.EntityState.Unchanged:
                return(Axerrio.Data.Entity.EntityState.Unchanged);

            case System.Data.Entity.EntityState.Added:
                return(Axerrio.Data.Entity.EntityState.Added);

            case System.Data.Entity.EntityState.Modified:
                return(Axerrio.Data.Entity.EntityState.Modified);

            case System.Data.Entity.EntityState.Deleted:
                return(Axerrio.Data.Entity.EntityState.Deleted);

            default:
                return(currentState);
            }
        }
示例#22
0
        public DomainBuildResult Build(Hatfield.EnviroData.DataProfile.WQ.Models.WQProfileEntity entity, Hatfield.EnviroData.Core.ODM2Entities dbContext)
        {
            var data = (Hatfield.EnviroData.DataProfile.WQ.Models.Site)entity;

            Hatfield.EnviroData.Core.Site  domain = null;
            System.Data.Entity.EntityState state  = EntityState.Unchanged;

            if (data == null)
            {
                throw new NullReferenceException("System fail to build domain on null entity.");
            }

            if (data.Id > 0)
            {
                domain = dbContext.Sites.Where(x => x.SamplingFeatureID == data.Id).FirstOrDefault();
            }

            //data has not change, return the data in the database
            if (!IsDataDirty(data, domain))
            {
                return(new DomainBuildResult(true, domain, EntityState.Unchanged));
            }

            //data is dirty
            if (domain == null)
            {
                domain = new Core.Site();
                state  = EntityState.Added;
            }
            else
            {
                state = EntityState.Modified;
            }

            domain.Latitude  = data.Latitude.HasValue ? data.Latitude.Value : domain.Latitude;
            domain.Longitude = data.Longitude.HasValue ? data.Longitude.Value : domain.Longitude;
            domain.SamplingFeature.SamplingFeatureName = data.Name;
            var result = new DomainBuildResult(true, domain, state);

            return(result);
        }
示例#23
0
        /// <summary>
        /// Updates the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        public override void Update(Model.Entities.User model)
        {
            // Detach existing Entity
            User existingEntity = Context.Set <User>().Find(ObjectMapper.GetEntityIdentifier <Model.Entities.User>(model));

            System.Data.Entity.EntityState existingState = Context.Entry <User>(existingEntity).State;
            if (existingState != System.Data.Entity.EntityState.Detached)
            {
                Context.Entry <User>(existingEntity).State = System.Data.Entity.EntityState.Detached;
            }

            User          updatedEntity = UserEntityFactory.CreateFromDomainModel(model, ObjectMapper);
            DbEntityEntry entry         = Context.Entry <User>(updatedEntity);

            if (entry.State == System.Data.Entity.EntityState.Detached)
            {
                //Context.Set<User>().Attach(updatedEntity);
                Context.Entry <User>(updatedEntity).State = System.Data.Entity.EntityState.Modified;
                Context.SaveChanges();
            }
        }
示例#24
0
        /// <summary>
        /// Updates the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        public virtual void Update(TModel model)
        {
            // Detach existing Entity
            TContextEntity existingEntity = Context.Set <TContextEntity>().Find(ObjectMapper.GetEntityIdentifier <TModel>(model));

            System.Data.Entity.EntityState existingState = Context.Entry <TContextEntity>(existingEntity).State;
            if (existingState != System.Data.Entity.EntityState.Detached)
            {
                Context.Entry <TContextEntity>(existingEntity).State = System.Data.Entity.EntityState.Detached;
            }

            TContextEntity updatedEntity = ObjectMapper.Map <TModel, TContextEntity>(model);
            DbEntityEntry  entry         = Context.Entry <TContextEntity>(updatedEntity);

            if (entry.State == System.Data.Entity.EntityState.Detached)
            {
                //Context.Set<TContextEntity>().Attach(updatedEntity);
                entry.State = System.Data.Entity.EntityState.Modified;
                Context.SaveChanges();
            }
        }
示例#25
0
        static EntityState GetEntityState(System.Data.Entity.EntityState entityStates)
        {
            switch (entityStates)
            {
            case System.Data.Entity.EntityState.Added:
                return(EntityState.Added);

            case System.Data.Entity.EntityState.Deleted:
                return(EntityState.Deleted);

            case System.Data.Entity.EntityState.Detached:
                return(EntityState.Detached);

            case System.Data.Entity.EntityState.Modified:
                return(EntityState.Modified);

            case System.Data.Entity.EntityState.Unchanged:
                return(EntityState.Unchanged);

            default:
                throw new NotImplementedException();
            }
        }
示例#26
0
        /// <summary>
        /// Updates the <see cref="EntityAttributesCache"/> based on the attribute and entityState
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="entityState">State of the entity.</param>
        internal static void UpdateCacheEntityAttributes(Rock.Model.Attribute attribute, System.Data.Entity.EntityState entityState)
        {
            var entityAttributesList = EntityAttributesCache.Get().EntityAttributes.ToList();

            if (entityAttributesList == null || attribute == null)
            {
                return;
            }

            bool listUpdated = false;

            if (entityState == EntityState.Deleted)
            {
                foreach (var entityAttributesItem in entityAttributesList.Where(a => a.AttributeIds.Contains(attribute.Id)))
                {
                    entityAttributesItem.AttributeIds.Remove(attribute.Id);
                    listUpdated = true;
                }
            }

            if (attribute?.EntityTypeId.HasValue == true)
            {
                if (entityState == EntityState.Modified)
                {
                    foreach (var entityAttributesItem in entityAttributesList.Where(a => a.AttributeIds.Contains(attribute.Id)))
                    {
                        if (entityAttributesItem.EntityTypeId != attribute.EntityTypeId || entityAttributesItem.EntityTypeQualifierColumn != attribute.EntityTypeQualifierColumn || entityAttributesItem.EntityTypeQualifierValue != attribute.EntityTypeQualifierValue)
                        {
                            entityAttributesItem.AttributeIds.Remove(attribute.Id);
                            listUpdated = true;
                        }
                    }
                }

                if (entityState == EntityState.Added || entityState == EntityState.Modified)
                {
                    var entityTypeEntityAttributesList = entityAttributesList.Where(a =>
                                                                                    a.EntityTypeId == attribute.EntityTypeId.Value &&
                                                                                    a.EntityTypeQualifierColumn == attribute.EntityTypeQualifierColumn &&
                                                                                    a.EntityTypeQualifierValue == attribute.EntityTypeQualifierValue);

                    if (entityTypeEntityAttributesList.Any())
                    {
                        foreach (var entityAttributes in entityTypeEntityAttributesList)
                        {
                            if (!entityAttributes.AttributeIds.Contains(attribute.Id))
                            {
                                entityAttributes.AttributeIds.Add(attribute.Id);
                                listUpdated = true;
                            }
                        }
                    }
                    else
                    {
                        entityAttributesList.Add(new EntityAttributes()
                        {
                            EntityTypeId = attribute.EntityTypeId,
                            EntityTypeQualifierColumn = attribute.EntityTypeQualifierColumn,
                            EntityTypeQualifierValue  = attribute.EntityTypeQualifierValue,
                            AttributeIds = new List <int>(new int[] { attribute.Id })
                        });

                        listUpdated = true;
                    }
                }
            }

            if (listUpdated)
            {
                var cache = EntityAttributesCache.Get();
                cache.EntityAttributes = entityAttributesList;
                cache.EntityAttributesByEntityTypeId = entityAttributesList.Where(a => a.EntityTypeId.HasValue).GroupBy(g => g.EntityTypeId.Value).ToDictionary(k => k.Key, v => v.ToList() ?? new List <EntityAttributes>());
                EntityAttributesCache.UpdateCacheItem(KEY, cache, TimeSpan.MaxValue);
            }
        }
示例#27
0
        /// <summary>
        /// Attach an entity to the context.  If it's already loaded, return the loaded entity.
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="entityState"></param>
        /// <returns></returns>
        private T Attach(T entity, System.Data.Entity.EntityState entityState)
        {
            if (entity == null)
            {
                return(null);
            }

            DbEntityEntry <T> entityEntry = context.Entry(entity);

            if (entityEntry.State == entityState)
            {
                return(entity);
            }

            if (entity != null && entityEntry.State == System.Data.Entity.EntityState.Detached)
            {
                if (entity is IEntity)
                {
                    // Get the entity's Id and look for an already loaded instance in EntitySet.Local.  If found, return the loaded entity.
                    Guid    id       = ((IEntity)entity).Id;
                    IEntity existing = EntitySet.Local.Cast <IEntity>().FirstOrDefault(p => p.Id == id);
                    if (existing != null)
                    {
                        return(existing as T);
                    }
                }
            }

            // EF makes attaching an object from another context very painful if that object contains other referenced entities.  Attach() can throw an exception if
            // any of the referenced entities were previously loaded into the context.

            // The first step is capture the state of all tracked entites in the context by storing them in a dictionary (keyed by entity.Id)
            var stateDict = new Dictionary <Guid, System.Data.Entity.EntityState>();

            foreach (var entry in context.ChangeTracker.Entries())
            {
                if (entry.Entity is IEntity)
                {
                    stateDict[((IEntity)entry.Entity).Id] = entry.State;
                }
            }

            // Then add the entity via the Add method.
            EntitySet.Add(entity);

            // Change the entity state to what we want it to be (Unmodified, or Modified)
            context.Entry(entity).State = entityState;

            // Finally check the state of all tracked entities, looking for ones that are in an Added State.
            foreach (var entry in context.ChangeTracker.Entries().Where(p => p.State == System.Data.Entity.EntityState.Added && p.Entity is IEntity))
            {
                System.Data.Entity.EntityState state;

                if (stateDict.TryGetValue(((IEntity)entry.Entity).Id, out state))
                {
                    // If the entity was already being tracked and wasn't originally in the Added state, detach the entity.
                    if (state != System.Data.Entity.EntityState.Added)
                    {
                        context.Entry(entry.Entity).State = System.Data.Entity.EntityState.Detached;
                    }
                }
                else
                {
                    // If the entity wasn't being tracked, make sure it's state is Unchanged.
                    context.Entry(entry.Entity).State = System.Data.Entity.EntityState.Unchanged;
                }
            }

            return(entity);
        }
示例#28
0
        /// <summary>
        /// Prepare list of Audit Logs from data properties
        /// </summary>
        /// <param name="dbEntry"></param>
        /// <param name="userId"></param>
        /// <param name="changeTime"></param>
        /// <param name="tableName"></param>
        /// <param name="keyName"></param>
        /// <param name="StatusPropertyId"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public List <AuditEntity> AddAuditFromDataProperties(DbEntityEntry dbEntry, long userId, DateTime changeTime,
                                                             string tableName, string primaryKeyName, string isActivePropertyId, string isDeletedProperty, System.Data.Entity.EntityState state)
        {
            List <AuditEntity> auditTrailsList = new List <AuditEntity>();

            //in case add new Entiry
            if (state == EntityState.Added)
            {
                // For Inserts, just add the whole record , the current state of the entity
                var xml = GetCurrents(dbEntry, userId, changeTime, tableName, primaryKeyName, isActivePropertyId, isDeletedProperty);
                //if no changes for some reason just return , no need to save empty xml ; a fail safe
                if (string.IsNullOrEmpty(xml))
                {
                    return(null);
                }
                auditTrailsList.Add(new AuditEntity()
                {
                    UserId    = userId,
                    LogDate   = changeTime,
                    EventType = "Add",
                    TableName = tableName,
                    RecordId  = dbEntry.CurrentValues.GetValue <object>(primaryKeyName).ToString(),
                    ChangeXml = xml,
                    IsData    = true
                });
            }
            return(auditTrailsList);
        }
示例#29
0
 public void ChangeState <TEntity>(TEntity entity, System.Data.Entity.EntityState newState) where TEntity : BaseEntity
 {
     this.Entry(entity).State = newState;
 }
示例#30
0
 public void ChangeState <TEntity>(TEntity entity, System.Data.Entity.EntityState newState) where TEntity : BaseEntity
 {
     Console.WriteLine("ChangeState ORIGINAL");
     this.Entry(entity).State = newState;
 }