예제 #1
0
        /// <summary>
        /// 批量更新审核状态
        /// </summary>
        /// <param name="ids">标签Id列表</param>
        /// <param name="isApproved">是否通过审核</param>
        public void UpdateAuditStatus(IEnumerable <long> ids, bool isApproved)
        {
            List <PetaPoco.Sql> sqls = new List <PetaPoco.Sql>();

            foreach (var id in ids)
            {
                var sql = PetaPoco.Sql.Builder;
                sql.Append("UPDATE tn_Tags SET AuditStatus = @0", isApproved ? (int)AuditStatus.Success : (int)AuditStatus.Fail)
                .Where("TagId = @0", id);
                sqls.Add(sql);
            }

            int affectCount = CreateDAO().Execute(sqls);

            //更新缓存版本号
            if (affectCount > 0)
            {
                AuditStatus status = isApproved ? AuditStatus.Success : AuditStatus.Fail;
                foreach (var id in ids)
                {
                    var tag = Get(id);
                    if (tag != null)
                    {
                        tag.AuditStatus = status;
                        RealTimeCacheHelper.IncreaseEntityCacheVersion(id);
                    }
                }

                RealTimeCacheHelper.IncreaseGlobalVersion();
            }
        }
예제 #2
0
        /// <summary>
        /// 更新隐私规则
        /// </summary>
        /// <param name="privacyItems">待更新的隐私项目规则集合</param>
        public void UpdatePrivacyItems(IEnumerable <PrivacyItem> privacyItems)
        {
            if (privacyItems == null)
            {
                return;
            }
            List <Sql> sqls = new List <Sql>();

            Database dao = CreateDAO();

            dao.OpenSharedConnection();
            foreach (var privacyItem in privacyItems)
            {
                sqls.Add(Sql.Builder.Append("update tn_PrivacyItems")
                         .Append("set ItemName = @0, Description = @1, DisplayOrder = @2, PrivacyStatus = @3", privacyItem.ItemName, privacyItem.Description, privacyItem.DisplayOrder, privacyItem.PrivacyStatus)
                         .Append("where ItemKey = @0 and ItemGroupId = @1 and ApplicationId = @2", privacyItem.ItemKey, privacyItem.ItemGroupId, privacyItem.ApplicationId));

                RealTimeCacheHelper.IncreaseEntityCacheVersion(privacyItem.ItemKey);
                OnUpdated(privacyItem);
            }
            dao.Execute(sqls);
            //done:zhangp,by zhengw:需要递增全局版本号
            dao.CloseSharedConnection();

            RealTimeCacheHelper.IncreaseGlobalVersion();
        }
예제 #3
0
        /// <summary>
        /// 取消关注后更新缓存
        /// </summary>
        /// <param name="sender">关注实体</param>
        /// <param name="eventArgs">事件参数</param>
        void CancelFollowEventModule_After(FollowEntity sender, CommonEventArgs eventArgs)
        {
            if (eventArgs.EventOperationType == EventOperationType.Instance().Delete())
            {
                CategoryService service = new CategoryService();
                service.ClearCategoriesFromItem(sender.Id, sender.UserId, TenantTypeIds.Instance().User());

                //更新用户缓存
                ICacheService       cacheService        = DIContainer.Resolve <ICacheService>();
                RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(User)).RealTimeCacheHelper;
                if (cacheService.EnableDistributedCache)
                {
                    realTimeCacheHelper.IncreaseEntityCacheVersion(sender.UserId);
                }
                else
                {
                    string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(sender.UserId);
                    User   user     = cacheService.Get <User>(cacheKey);
                    if (user != null && user.FollowedCount > 0)
                    {
                        user.FollowedCount--;
                    }
                }
            }
        }
예제 #4
0
        /// <summary>
        /// 批量更新审核状态
        /// </summary>
        /// <param name="ids">评论Id列表</param>
        /// <param name="auditingStatus">审核状态</param>
        public void UpdateAuditStatus(IEnumerable <long> ids, AuditStatus auditStatus)
        {
            //声明PetaPoco的SqlBuilder
            var sql = PetaPoco.Sql.Builder;

            //组装sql
            sql.Append("update tn_Categories set AuditStatus =@0", (int)auditStatus)
            .Where("CategoryId in (@ids)", new { ids = ids });

            //执行语句
            int effectLineCount = CreateDAO().Execute(sql);

            #region 处理缓存

            if (effectLineCount > 0)
            {
                //更新实体缓存
                foreach (long id in ids)
                {
                    T category = Get(id);
                    if (category != null)
                    {
                        category.AuditStatus = auditStatus;
                    }
                    RealTimeCacheHelper.IncreaseEntityCacheVersion(id);
                }

                //处理全局缓存 - 后台管理,需要即时显示
                RealTimeCacheHelper.IncreaseGlobalVersion();
            }
            #endregion
        }
예제 #5
0
        /// <summary>
        /// 批量关注积分处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        void BatchFollowPointModule_After(int sender, BatchFollowEventArgs eventArgs)
        {
            if (EventOperationType.Instance().Create() == eventArgs.EventOperationType && sender > 0)
            {
                string pointItemKey = string.Empty;
                pointItemKey = PointItemKeys.Instance().FollowUser();
                PointService pointService = new PointService();

                for (int i = 0; i < sender; i++)
                {
                    pointService.GenerateByRole(eventArgs.UserId, pointItemKey, "批量添加关注");
                }

                //更新用户缓存
                ICacheService       cacheService        = DIContainer.Resolve <ICacheService>();
                RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(User)).RealTimeCacheHelper;
                if (cacheService.EnableDistributedCache)
                {
                    realTimeCacheHelper.IncreaseEntityCacheVersion(eventArgs.UserId);
                }
                else
                {
                    string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(eventArgs.UserId);
                    User   user     = cacheService.Get <User>(cacheKey);
                    if (user != null)
                    {
                        user.FollowedCount = user.FollowedCount + sender;
                    }
                }
            }
        }
예제 #6
0
 /// <summary>
 /// 数据库删除实体后自动调用该方法
 /// </summary>
 /// <param name="entity"></param>
 protected virtual void OnDeleted(TEntity entity)
 {
     #region 处理缓存
     if (RealTimeCacheHelper.EnableCache)
     {
         //递增实体缓存版本
         RealTimeCacheHelper.IncreaseEntityCacheVersion(entity.EntityId);
         //更新列表缓存版本
         RealTimeCacheHelper.IncreaseListCacheVersion(entity);
         cacheService.MarkDeletion(RealTimeCacheHelper.GetCacheKeyOfEntity(entity.EntityId), entity, CachingExpirationType.SingleObject);
     }
     #endregion
 }
예제 #7
0
        /// <summary>
        /// 更新敏感词
        /// </summary>
        /// <param name="sensitiveWord"></param>
        /// <returns></returns>
        public int Update(SensitiveWord sensitiveWord)
        {
            int id = CreateDAO().ExecuteScalar <int>(Sql.Builder.Append("select Id from tn_SensitiveWords where Word = @0", sensitiveWord.Word));

            RealTimeCacheHelper.IncreaseEntityCacheVersion(sensitiveWord.Id);
            cacheService.Remove(RealTimeCacheHelper.GetCacheKeyOfEntity(sensitiveWord.Id));

            if (id > 0 && id != sensitiveWord.Id)
            {
                return(-1);
            }
            base.Update(sensitiveWord);
            return(sensitiveWord.Id);
        }
예제 #8
0
        /// <summary>
        /// 清除用户所有私信会话
        /// </summary>
        /// <param name="userId">用户Id</param>
        public void ClearSessionsFromUser(long userId)
        {
            Database dao = CreateDAO();

            dao.OpenSharedConnection();

            List <Sql> sqls = new List <Sql>();
            var        sql  = Sql.Builder;

            sql.Select("SessionId")
            .From("tn_MessageSessions")
            .Where("UserId = @0", userId);
            IEnumerable <object> sessionids = dao.FetchFirstColumn(sql);

            if (sessionids.Count() > 0)
            {
                //清除私信实体脚本
                sqls.Add(Sql.Builder.Append("delete from tn_Messages where exists(")
                         .Append("select 1 from tn_MessagesInSessions MIS where tn_Messages.MessageId = MIS.MessageId and exists(")
                         .Append("select 1 from tn_MessageSessions MS where MS.SessionId = MIS.SessionId and MS.UserId = @0 and not exists(", userId)
                         .Append("select 1 from tn_MessageSessions SUBMS Where SUBMS.UserId = MS.OtherUserId and SUBMS.OtherUserId = MS.UserId)))"));

                //清除私信与会话关联脚本
                sqls.Add(Sql.Builder.Append("delete from tn_MessagesInSessions where exists(")
                         .Append("select 1 from tn_MessageSessions MS where MS.SessionId = tn_MessagesInSessions.SessionId and MS.UserId = @0)", userId));

                //清除私信会话
                sqls.Add(Sql.Builder.Append("delete from tn_MessageSessions where UserId = @0", userId));

                using (var transaction = dao.GetTransaction())
                {
                    dao.Execute(sqls);
                    transaction.Complete();
                }
            }

            dao.CloseSharedConnection();

            #region 更新缓存

            RealTimeCacheHelper.IncreaseAreaVersion("UserId", userId);

            sessionids.ToList().ForEach((n) =>
            {
                RealTimeCacheHelper.IncreaseEntityCacheVersion(n);
            });

            #endregion
        }
예제 #9
0
        /// <summary>
        /// 仅更新实体属性
        /// </summary>
        /// <param name="category">要更新的分类</param>
        public void UpdateItemCount(T category)
        {
            //声明PetaPoco的SqlBuilder
            var sql = PetaPoco.Sql.Builder;

            //组装sql
            sql.Append("update tn_Categories set ItemCount =@0", category.ItemCount)
            .Where("CategoryId = @0", category.CategoryId);

            //执行语句
            int effectLineCount = CreateDAO().Execute(sql);

            //更新缓存
            if (effectLineCount > 0)
            {
                RealTimeCacheHelper.IncreaseEntityCacheVersion(category.CategoryId);
            }
        }
예제 #10
0
        /// <summary>
        /// 更新类别,注意:不能更新ParentId属性!
        /// </summary>
        /// <param name="category">待更新的类别</param>
        public void Update(T category)
        {
            //声明PetaPoco的SqlBuilder
            var sql = PetaPoco.Sql.Builder;

            //组装sql
            sql.Append("update tn_Categories  set CategoryName = @0 ,Description =@1,DisplayOrder=@2,Depth=@3,ChildCount=@4,ItemCount=@5,PrivacyStatus=@6,AuditStatus=@7,FeaturedItemId=@8,LastModified=@9,PropertyNames=@10,PropertyValues=@11", category.CategoryName, category.Description, category.DisplayOrder, category.Depth, category.ChildCount, category.ItemCount, category.PrivacyStatus, category.AuditStatus, category.FeaturedItemId, category.LastModified, category.PropertyNames, category.PropertyValues)
            .Where("CategoryId = @0", category.CategoryId);

            //执行语句
            int effectLineCount = CreateDAO().Execute(sql);

            #region 处理缓存

            RealTimeCacheHelper.IncreaseEntityCacheVersion(category);

            #endregion
        }
예제 #11
0
        /// <summary>
        /// 删除UserId相关的附件
        /// </summary>
        /// <param name="userId">上传者Id</param>
        public void DeletesByUserId(string tenantTypeId, long userId)
        {
            var sql = PetaPoco.Sql.Builder;

            sql.Append("DELETE  FROM tn_Attachments").Where("TenantTypeId=@0 and UserId=@1", tenantTypeId, userId);

            int affectCount = CreateDAO().Execute(sql);

            if (affectCount > 0)
            {
                //更新缓存
                RealTimeCacheHelper.IncreaseAreaVersion("UserId", userId);
                IEnumerable <object> attachmentIds = GetIdsByUserId(tenantTypeId, userId);
                foreach (var id in attachmentIds.Cast <long>())
                {
                    RealTimeCacheHelper.IncreaseEntityCacheVersion(id);
                }
            }
        }
예제 #12
0
        /// <summary>
        /// 更新最后下载时间
        /// </summary>
        /// <param name="userId">下载用户UserId</param>
        /// <param name="attachmentId">附件Id</param>
        public bool UpdateLastDownloadDate(long userId, long attachmentId)
        {
            var sql = PetaPoco.Sql.Builder;

            sql.Append("Update tn_AttachmentDownloadRecords set LastDownloadDate = @0", DateTime.UtcNow)
            .Where("UserId = @0 and AttachmentId = @1", userId, attachmentId);

            int count = CreateDAO().Execute(sql);

            Dictionary <long, long> ids_AttachmentIds = GetIds_AttachmentIdsByUser(userId);

            if (ids_AttachmentIds != null && ids_AttachmentIds.Values.Contains(attachmentId))
            {
                //更新实体缓存
                RealTimeCacheHelper.IncreaseEntityCacheVersion(ids_AttachmentIds.FirstOrDefault(n => n.Value == attachmentId).Key);
            }

            return(count > 0);
        }
예제 #13
0
        /// <summary>
        /// 变更系统数据
        /// </summary>
        /// <param name="dataKey">数据标识</param>
        /// <param name="number">待变更的数值</param>
        public void Change(string dataKey, long number)
        {
            //当DataKey不存在时,插入新数据

            Database   dao        = CreateDAO();
            SystemData systemData = Get(dataKey);

            if (systemData == null)
            {
                systemData           = new SystemData();
                systemData.Datakey   = dataKey;
                systemData.LongValue = number;
                dao.Insert(systemData);
            }
            else
            {
                systemData.LongValue += number;
                dao.Update(systemData);
            }
            RealTimeCacheHelper.IncreaseEntityCacheVersion(systemData);
        }
예제 #14
0
        /// <summary>
        /// 变更应用数据
        /// </summary>
        /// <param name="applicationId">应用Id</param>
        /// <param name="dataKey">数据标识</param>
        /// <param name="value">待变更的值</param>
        public void Change(int applicationId, string dataKey, string value)
        {
            Database        dao             = CreateDAO();
            ApplicationData applicationData = Get(applicationId, dataKey);

            if (applicationData == null)
            {
                applicationData = new ApplicationData();
                applicationData.ApplicationId = applicationId;
                applicationData.Datakey       = dataKey;
                applicationData.TenantTypeId  = string.Empty;
                applicationData.StringValue   = value;
                dao.Insert(applicationData);
            }
            else
            {
                applicationData.StringValue = value;
                dao.Update(applicationData);
            }
            RealTimeCacheHelper.IncreaseEntityCacheVersion(applicationData);
        }
예제 #15
0
        /// <summary>
        /// 相册隐私状态更改,同步更改相册下隐私状态
        /// </summary>
        /// <param name="albumId"></param>
        public void UpdatePrivacyStatus(long albumId)
        {
            var dao = CreateDAO();

            dao.OpenSharedConnection();

            Album album = new PhotoService().GetAlbum(albumId);

            if (album != null)
            {
                Sql sql = Sql.Builder
                          .Append("update spb_Photos set PrivacyStatus = @0 where spb_Photos.AlbumId = @1", album.PrivacyStatus, albumId);
                dao.Execute(sql);
            }

            Sql sql_Select = Sql.Builder
                             .Select("PhotoId")
                             .From("spb_Photos");

            IEnumerable <object> photoIds = dao.FetchTopPrimaryKeys <Photo>(int.MaxValue, sql_Select);

            dao.CloseSharedConnection();

            foreach (var item in photoIds)
            {
                long id = 0;
                if (long.TryParse(item.ToString(), out id))
                {
                    RealTimeCacheHelper.IncreaseEntityCacheVersion(id);

                    //处理掉本机缓存
                    string cacheKeyOfEntity = RealTimeCacheHelper.GetCacheKeyOfEntity(id);
                    Photo  photo            = cacheService.Get <Photo>(cacheKeyOfEntity);
                    if (photo != null)
                    {
                        photo.IsEssential = true;
                    }
                }
            }
        }
예제 #16
0
 /// <summary>
 /// 关注后更新缓存
 /// </summary>
 /// <param name="sender">关注实体</param>
 /// <param name="eventArgs">事件参数</param>
 void FollowUpdateCountModule_After(FollowEntity sender, CommonEventArgs eventArgs)
 {
     if (eventArgs.EventOperationType == EventOperationType.Instance().Create())
     {
         //更新用户缓存
         ICacheService       cacheService        = DIContainer.Resolve <ICacheService>();
         RealTimeCacheHelper realTimeCacheHelper = EntityData.ForType(typeof(User)).RealTimeCacheHelper;
         if (cacheService.EnableDistributedCache)
         {
             realTimeCacheHelper.IncreaseEntityCacheVersion(sender.UserId);
         }
         else
         {
             string cacheKey = realTimeCacheHelper.GetCacheKeyOfEntity(sender.UserId);
             User   user     = cacheService.Get <User>(cacheKey);
             if (user != null)
             {
                 user.FollowedCount++;
             }
         }
     }
 }
예제 #17
0
        /// <summary>
        /// 更新父级ChildCount
        /// </summary>
        /// <param name="parentId">父级Id</param>
        /// <param name="isReduce">是否减少</param>
        public void UpdateChildCount(long parentId, bool isReduce)
        {
            var sql = PetaPoco.Sql.Builder;

            if (isReduce)
            {
                sql.Append(" UPDATE tn_Comments Set ChildCount=ChildCount-1 ").Where("Id =@0", parentId);
            }
            else
            {
                sql.Append(" UPDATE tn_Comments Set ChildCount=ChildCount+1 ").Where("Id =@0", parentId);
            }

            int rows = CreateDAO().Execute(sql);

            #region 处理缓存
            if (rows > 0)
            {
                RealTimeCacheHelper.IncreaseEntityCacheVersion(parentId);
            }
            #endregion
        }
예제 #18
0
        /// <summary>
        /// 批量更改处理状态
        /// </summary>
        /// <param name="userId">用户的id</param>
        /// <param name="status">要更改的状态</param>
        public void BatchSetStatus(long userId, InvitationStatus status)
        {
            Database dao = CreateDAO();
            var      sql = PetaPoco.Sql.Builder;

            sql.Select("Id")
            .From("tn_Invitations")
            .Where("UserId=@0 and Status=@1", userId, (int)InvitationStatus.Unhandled);

            dao.OpenSharedConnection();
            IEnumerable <object> ids = dao.FetchFirstColumn(sql);

            sql = PetaPoco.Sql.Builder;
            sql.Append("update tn_Invitations set Status=@0 where UserId=@1 and Status =@2", (int)status, userId, (int)InvitationStatus.Unhandled);
            dao.Execute(sql);
            dao.CloseSharedConnection();

            //维护缓存
            string cacheKey = GetCacheKey_UnhandledInvitationCount(userId);
            int?   count    = cacheService.Get(cacheKey) as int?;

            if (count != null)
            {
                count = 0;
                cacheService.Set(cacheKey, count, CachingExpirationType.SingleObject);
            }
            //更新列表缓存
            RealTimeCacheHelper.IncreaseAreaVersion("UserId", userId);
            //更新实体缓存
            foreach (var id in ids)
            {
                Invitation invitation = Get(id);
                if (invitation != null)
                {
                    invitation.Status = status;
                }
                RealTimeCacheHelper.IncreaseEntityCacheVersion(id);
            }
        }
예제 #19
0
        /// <summary>
        /// 数据库更新实体后自动调用该方法
        /// </summary>
        protected virtual void OnUpdated(TEntity entity)
        {
            #region 处理缓存
            if (RealTimeCacheHelper.EnableCache)
            {
                //更新实体缓存版本
                RealTimeCacheHelper.IncreaseEntityCacheVersion(entity.EntityId);
                //更新列表缓存版本
                RealTimeCacheHelper.IncreaseListCacheVersion(entity);

                if (RealTimeCacheHelper.PropertyNameOfBody != null && RealTimeCacheHelper.PropertyNameOfBody.GetValue(entity, null) != null)
                {
                    string body = RealTimeCacheHelper.PropertyNameOfBody.GetValue(entity, null) as string;
                    cacheService.Set(RealTimeCacheHelper.GetCacheKeyOfEntityBody(entity.EntityId), body, RealTimeCacheHelper.CachingExpirationType);

                    //启用实体正文缓存时,不在实体缓存中存储实体正文
                    RealTimeCacheHelper.PropertyNameOfBody.SetValue(entity, null, null);
                }
                cacheService.Set(RealTimeCacheHelper.GetCacheKeyOfEntity(entity.EntityId), entity, RealTimeCacheHelper.CachingExpirationType);
            }

            #endregion
        }
예제 #20
0
        /// <summary>
        /// 批量将所有未处理通知修改为已处理状态
        /// </summary>
        /// <param name="userId">接收人Id</param>
        public void BatchSetIsHandled(long userId)
        {
            Database dao = CreateDAO();
            var      sql = PetaPoco.Sql.Builder;

            sql.Select("Id").From("tn_Notices")
            .Where("UserId=@0", userId)
            .Where("Status=@0", (int)NoticeStatus.Unhandled);
            IEnumerable <object> ids_object = dao.FetchFirstColumn(sql);
            IEnumerable <long>   ids        = ids_object.Cast <long>();

            sql = PetaPoco.Sql.Builder;
            sql.Append("UPDATE tn_Notices Set Status=@0", (int)NoticeStatus.Handled)
            .Where("UserId=@0", userId)
            .Where("Status=@0", (int)NoticeStatus.Unhandled);
            dao.Execute(sql);
            //更新缓存
            foreach (long id in ids)
            {
                Notice notice = Get(id);
                if (notice != null)
                {
                    notice.Status = NoticeStatus.Handled;
                }
                RealTimeCacheHelper.IncreaseEntityCacheVersion(id);
            }

            string cacheKey = GetCacheKey_UnhandledNoticeCount(userId);
            int?   count    = cacheService.Get(cacheKey) as int?;

            if (count != null)
            {
                count = 0;
                cacheService.Set(cacheKey, count, CachingExpirationType.SingleObject);
            }
            RealTimeCacheHelper.IncreaseAreaVersion("UserId", userId);
        }
예제 #21
0
        /// <summary>
        /// 更新请求状态
        /// </summary>
        /// <param name="invitation">状态的id</param>
        /// <param name="status">要更新的状态</param>
        public void SetStatus(Invitation invitation, InvitationStatus status)
        {
            var sql = PetaPoco.Sql.Builder;

            sql.Append("update tn_Invitations set Status=@0 where id=@1", (int)status, invitation.Id);
            CreateDAO().Execute(sql);
            #region 处理缓存
            string cacheKey = GetCacheKey_UnhandledInvitationCount(invitation.UserId);
            int?   count    = cacheService.Get(cacheKey) as int?;
            if (count != null)
            {
                count--;
                if (count >= 0)
                {
                    cacheService.Set(cacheKey, count, CachingExpirationType.SingleObject);
                }
            }

            //解决非分布式缓存情况下更新实体缓存问题
            invitation.Status = status;
            RealTimeCacheHelper.IncreaseAreaVersion("UserId", invitation.UserId);
            RealTimeCacheHelper.IncreaseEntityCacheVersion(invitation.Id);
            #endregion
        }
예제 #22
0
        /// <summary>
        /// 从fromCategoryId并入到toCategoryId
        /// </summary>
        /// <remarks>
        /// 例如:将分类fromCategoryId合并到分类toCategoryId,那么fromCategoryId分类下的所有子分类和实体全部归到toCategoryId分类,同时删除fromCategoryId分类
        /// </remarks>
        /// <param name="fromCategoryId">源类别</param>
        /// <param name="toCategoryId">目标类别</param>
        public void Merge(long fromCategoryId, long toCategoryId)
        {
            //为处理缓存做准备
            T fromCategory = Get(fromCategoryId);

            #region 组装sql

            //1 将所有的子分类合并到toCategoryId下
            var sql_ChildCategoryUpdate = PetaPoco.Sql.Builder;
            sql_ChildCategoryUpdate.Append("update tn_Categories set ParentId = @0", toCategoryId).Where("ParentId = @0", fromCategoryId);

            //2 将fromCategoryId下的所有直属实体类合并到toCategoryId下
            var sql_ChildItemsUpdate = PetaPoco.Sql.Builder;
            sql_ChildItemsUpdate.Append("update tn_ItemsInCategories set CategoryId = @0", toCategoryId).Where("CategoryId = @0", fromCategoryId);

            //3 更新后代分类深度
            //获得所有fromCategory的后代Category
            T               toCategory          = Get(toCategoryId);
            IList <T>       fromChildCategories = new List <T>();
            IEnumerable <T> ownerCategories     = GetOwnerCategories(toCategory.OwnerId, toCategory.TenantTypeId);
            this.RecurseGetChildren(fromCategory, fromChildCategories, ownerCategories.ToList());

            //循环更新fromCategory每一个后代Category的Depth
            IList <Sql> sql_UpdateFromChildCategoryDepths = new List <Sql>();
            foreach (T fromChildCategory in fromChildCategories)
            {
                int fromChildCategoryDepth = toCategory.Depth + fromChildCategory.Depth - fromCategory.Depth;
                fromChildCategory.Depth = fromChildCategoryDepth;
                sql_UpdateFromChildCategoryDepths.Add(Sql.Builder.Append("update tn_Categories set Depth = @0", fromChildCategoryDepth).Where("CategoryId=@0", fromChildCategory.CategoryId));
            }

            //4 修改toCategory 的属性:ChildCount,ItemCount
            //见下:sql_ToCategoryChildCountUpdate

            //5 最后删除fromCategory
            var sql_FromCategoryDelete = PetaPoco.Sql.Builder;
            sql_FromCategoryDelete.Append("delete tn_Categories").Where("CategoryId = @0", fromCategoryId);

            //6 修改原先from的父级分类的子分类数减一
            var sql_FromParentCategoryChildCountUpdate = PetaPoco.Sql.Builder;
            if (fromCategory.ParentId > 0)
            {
                sql_FromParentCategoryChildCountUpdate.Append("update tn_Categories set ChildCount = ChildCount-1 ").Where("ChildCount > 0 and CategoryId = @0", fromCategory.ParentId);
            }

            #endregion

            int childCategoryCount    = 0 /*子分类数*/,
                childItemCount        = 0 /*内容数*/,
                updateToCategoryCount = 0,
                deleteEffectLineCount = 0,
                affectCount           = 0,
                updateDepthCount      = 0;

            PetaPocoDatabase dao = CreateDAO();
            //在同一个事务中执行
            using (var scope = dao.GetTransaction())
            {
                //1
                childCategoryCount = dao.Execute(sql_ChildCategoryUpdate);
                //2
                childItemCount = dao.Execute(sql_ChildItemsUpdate);
                //3
                var sql_ToCategoryChildCountUpdate = PetaPoco.Sql.Builder;
                sql_ToCategoryChildCountUpdate.Append("update tn_Categories set ChildCount =ChildCount + @0,ItemCount=ItemCount + @1", childCategoryCount, childItemCount).Where("CategoryId = @0", toCategoryId);
                updateToCategoryCount = dao.Execute(sql_ToCategoryChildCountUpdate);
                //4
                updateDepthCount = dao.Execute(sql_UpdateFromChildCategoryDepths);
                //5
                deleteEffectLineCount = dao.Execute(sql_FromCategoryDelete);
                //6
                if (fromCategory.ParentId > 0)
                {
                    affectCount = dao.Execute(sql_FromParentCategoryChildCountUpdate);
                }

                //事务结束
                scope.Complete();
            }

            #region 缓存处理

            //标记删除
            if (deleteEffectLineCount > 0)
            {
                RealTimeCacheHelper.MarkDeletion(fromCategory);
            }

            if (updateToCategoryCount > 0)
            {
                //实体缓存,toCategory
                RealTimeCacheHelper.IncreaseEntityCacheVersion(toCategoryId);

                //处理所有的列表缓存toCategory 相关的列表
                RealTimeCacheHelper.IncreaseAreaVersion("OwnerId", toCategory.OwnerId);
                RealTimeCacheHelper.IncreaseAreaVersion("ParentId", toCategory.CategoryId);

                //处理全局缓存(后台管理)
                RealTimeCacheHelper.IncreaseGlobalVersion();
            }

            if (updateDepthCount > 0 && ownerCategories.Count() > 1)
            {
                foreach (var ownerCategory in ownerCategories)
                {
                    if (ownerCategory.ParentId == fromCategoryId)
                    {
                        ownerCategory.ParentId = toCategoryId;
                    }

                    RealTimeCacheHelper.IncreaseEntityCacheVersion(ownerCategory.CategoryId);
                }
            }

            //处理分类下的内容项的缓存
            if (childItemCount > 0)
            {
                //toCategory以及父级
                List <long> toCategoryParentsIds = new List <long>();
                RecurseGetParents(toCategoryId, toCategoryParentsIds);
                toCategoryParentsIds.Add(toCategoryId);
                foreach (long categoryId in toCategoryParentsIds)
                {
                    EntityData.ForType(typeof(ItemInCategory)).RealTimeCacheHelper.IncreaseAreaVersion("CategoryId", toCategoryId);
                }

                //fromCategory父级
                List <long> fromCategoryParentsIds = new List <long>();
                RecurseGetParents(fromCategoryId, fromCategoryParentsIds);
                foreach (long categoryId in fromCategoryParentsIds)
                {
                    EntityData.ForType(typeof(ItemInCategory)).RealTimeCacheHelper.IncreaseAreaVersion("CategoryId", toCategoryId);
                }
            }

            #endregion
        }
예제 #23
0
        /// <summary>
        /// 把fromCategoryId移动到toCategoryId
        /// </summary>
        /// <remarks>
        /// 将一个分类移动到另一个分类,并作为另一个分类的子分类
        /// </remarks>
        /// <param name="fromCategoryId">被移动类别</param>
        /// <param name="toCategoryId">目标类别</param>
        public void Move(long fromCategoryId, long toCategoryId)
        {
            //初始分类实体
            T fromCategory = Get(fromCategoryId);

            //目标分类实体
            T toCategory = Get(toCategoryId);

            IList <PetaPoco.Sql> sqls = new List <PetaPoco.Sql>();

            //1 修改本分类的ParentID
            var sql_UpdateFromCategory = PetaPoco.Sql.Builder;

            sql_UpdateFromCategory.Append("update tn_Categories set ParentId = @0", toCategoryId).Where("CategoryId=@0", fromCategoryId);
            sqls.Add(sql_UpdateFromCategory);

            //2 更新本分类及所有后代分类的Depth
            //获得所有fromCategory的后代Category
            IList <T>       fromChildCategories = new List <T>();
            IEnumerable <T> ownerCategories     = GetOwnerCategories(toCategory.OwnerId, toCategory.TenantTypeId);

            this.RecurseGetChildren(fromCategory, fromChildCategories, ownerCategories.ToList());

            //更新fromCategory的Depth
            int fromCategoryDepth = toCategory.Depth + 1;

            var sql_UpdateFromCategoryDepth = PetaPoco.Sql.Builder;

            sql_UpdateFromCategoryDepth.Append("update tn_Categories set Depth = @0", fromCategoryDepth).Where("CategoryId=@0", fromCategory.CategoryId);
            sqls.Add(sql_UpdateFromCategoryDepth);

            //循环更新fromCategory每一个后代Category的Depth
            foreach (T fromChildCategory in fromChildCategories)
            {
                int fromChildCategoryDepth = fromCategoryDepth + fromChildCategory.Depth - fromCategory.Depth;
                fromChildCategory.Depth = fromChildCategoryDepth;
                var sql_UpdateFromChildCategoryDepth = PetaPoco.Sql.Builder;
                sql_UpdateFromChildCategoryDepth.Append("update tn_Categories set Depth = @0", fromChildCategoryDepth).Where("CategoryId=@0", fromChildCategory.CategoryId);
                sqls.Add(sql_UpdateFromChildCategoryDepth);
            }

            //3 toCategory的ChildCount+1
            var sql_UpdateToCategory = PetaPoco.Sql.Builder;

            sql_UpdateToCategory.Append("update tn_Categories set ChildCount = ChildCount+1 ").Where("CategoryId=@0", toCategoryId);
            sqls.Add(sql_UpdateToCategory);

            //4 fromCategory的Parent的ChildCount-1
            var sql_UpdateFromParentCategory = PetaPoco.Sql.Builder;

            if (fromCategory.ParentId > 0)
            {
                sql_UpdateFromParentCategory.Append("update tn_Categories set ChildCount = ChildCount-1 ").Where("ChildCount > 0 and CategoryId = @0", fromCategory.ParentId);
                sqls.Add(sql_UpdateFromParentCategory);
            }

            //影响的行数
            int effectLineCount = 0;

            PetaPocoDatabase dao = CreateDAO();

            //使用事务
            using (var scope = dao.GetTransaction())
            {
                effectLineCount = dao.Execute(sqls);

                //事务结束
                scope.Complete();
            }

            #region 处理缓存

            if (effectLineCount > 0)
            {
                //单体缓存fromCategory,toCategory,fromParentCategory
                RealTimeCacheHelper.IncreaseEntityCacheVersion(fromCategoryId);
                RealTimeCacheHelper.IncreaseEntityCacheVersion(toCategoryId);
                if (fromCategory.ParentId > 0)
                {
                    RealTimeCacheHelper.IncreaseEntityCacheVersion(fromCategory.ParentId);
                }
                fromCategory.ParentId = toCategory.CategoryId;
                fromCategory.Depth    = toCategory.Depth + 1;

                //列表缓存
                RealTimeCacheHelper.IncreaseAreaVersion("OwnerId", toCategory.OwnerId);     //该用户的缓存
                RealTimeCacheHelper.IncreaseAreaVersion("ParentId", toCategory.ParentId);   //父级分类列表缓存
                RealTimeCacheHelper.IncreaseAreaVersion("ParentId", toCategory.CategoryId); //本级分类列表缓存
                RealTimeCacheHelper.IncreaseAreaVersion("ParentId", fromCategory.CategoryId);

                if (ownerCategories.Count() > 1)
                {
                    foreach (var ownerCategory in ownerCategories)
                    {
                        RealTimeCacheHelper.IncreaseEntityCacheVersion(ownerCategory.CategoryId);
                    }
                }


                //全局缓存
                RealTimeCacheHelper.IncreaseGlobalVersion();

                //处理内容项对应的缓存
                //toCategory以及父级
                List <long> toCategoryParentsIds = new List <long>();
                RecurseGetParents(toCategoryId, toCategoryParentsIds);
                toCategoryParentsIds.Add(toCategoryId);
                foreach (long categoryId in toCategoryParentsIds)
                {
                    EntityData.ForType(typeof(ItemInCategory)).RealTimeCacheHelper.IncreaseAreaVersion("CategoryId", toCategoryId);
                }

                //fromCategory父级
                List <long> fromCategoryParentsIds = new List <long>();
                RecurseGetParents(fromCategoryId, fromCategoryParentsIds);
                foreach (long categoryId in fromCategoryParentsIds)
                {
                    EntityData.ForType(typeof(ItemInCategory)).RealTimeCacheHelper.IncreaseAreaVersion("CategoryId", toCategoryId);
                }
            }
            #endregion
        }