public void CreateComparerTest()
        {
            List <int> list1 = new List <int>();

            for (int i = 0; i < 100; i++)
            {
                list1.Add(i);
            }
            List <int> list2 = new List <int>();

            for (int i = 50; i < 150; i++)
            {
                list2.Add(i);
            }
            IEqualityComparer <int> comparer = EqualityHelper <int> .CreateComparer(m => m);

            List <int> list3 = list1.Intersect(list2, comparer).ToList();

            Assert.Equal(50, list3.Count);
            Assert.Equal(50, list3.Min());
            Assert.Equal(99, list3.Max());
            List <int> list4 = list1.Except(list2, comparer).ToList();

            Assert.Equal(50, list4.Count);
            Assert.Equal(0, list4.Min());
            Assert.Equal(49, list4.Max());
        }
示例#2
0
        /// <summary>
        /// 设置角色权限
        /// </summary>
        /// <param name="input">角色权限input</param>
        /// <returns>业务操作结果</returns>
        public async Task GrantPermissions(GrantRolePermissionInput input)
        {
            var permissions = PermissionManager.GetAllPermissions().Where(p => input.PermissionNames.Contains(p.Name));

            //自动添加父级权限
            var fullPermissions = new List <Permission>(permissions);

            foreach (var permission in permissions)
            {
                var parent = permission.Parent;
                while (parent != null)
                {
                    if (!fullPermissions.Contains(parent, EqualityHelper <Permission> .CreateComparer(p => p.Name)))
                    {
                        fullPermissions.Add(parent);
                    }
                    parent = parent.Parent;
                }
            }

            await _roleManager.SetGrantedPermissionsAsync(input.RoleId, fullPermissions);
        }
        /// <summary>
        /// 根据指定用户添加用户角色映射信息
        /// </summary>
        /// <param name="dtos">要添加的用户角色映射信息DTO信息</param>
        /// <returns>业务操作结果</returns>
        public async Task <OperationResult> AddUserRoleMapsByUser(params UserRoleMapDto[] dtos)
        {
            dtos.CheckNotNull("dtos");
            var uid  = dtos[0].UserId;
            var list = UserRoleMaps.Where(c => c.UserId == uid).Select(m => new UserRoleMapDto
            {
                Id     = m.Id,
                UserId = m.UserId,
                RoleId = m.RoleId
            }).ToList();
            //删除移除的用户
            var             removeItems = list.Except(dtos, EqualityHelper <UserRoleMapDto> .CreateComparer(m => m.RoleId + m.UserId)).Select(m => m.Id).ToArray();
            OperationResult result      = await DeleteUserRoleMaps(removeItems);

            //添加新增的用户
            var items = dtos.Except(list, EqualityHelper <UserRoleMapDto> .CreateComparer(m => m.RoleId + m.UserId)).ToArray();

            if (items.Count() > 0)
            {
                result = await Task.FromResult(UserRoleMapRepository.Insert(items));
            }
            return(result);
        }
示例#4
0
        /// <summary>
        /// 将从程序集获取的功能信息同步到数据库中
        /// </summary>
        /// <param name="scopedProvider">局部服务程序提供者</param>
        /// <param name="functions">程序集获取的功能信息</param>
        protected virtual void SyncToDatabase(IServiceProvider scopedProvider, TFunction[] functions)
        {
            Check.NotNull(functions, nameof(functions));
            if (functions.Length == 0)
            {
                return;
            }

            IRepository <TFunction, Guid> repository = scopedProvider.GetService <IRepository <TFunction, Guid> >();

            if (repository == null)
            {
                throw new OsharpException("IRepository<,>的服务未找到,请初始化 EntityFrameworkCoreModule 模块");
            }
            TFunction[] dbItems = repository.TrackEntities.ToArray();

            //删除的功能
            TFunction[] removeItems = dbItems.Except(functions,
                                                     EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action)).ToArray();
            int removeCount = removeItems.Length;

            //todo:由于外键关联不能物理删除的实体,需要实现逻辑删除
            repository.Delete(removeItems);

            //新增的功能
            TFunction[] addItems = functions.Except(dbItems,
                                                    EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action)).ToArray();
            int addCount = addItems.Length;

            repository.Insert(addItems);

            //更新的功能信息
            int updateCount = 0;

            foreach (TFunction item in dbItems.Except(removeItems))
            {
                bool      isUpdate = false;
                TFunction function;
                try
                {
                    function = functions.Single(m =>
                                                string.Equals(m.Area, item.Area, StringComparison.OrdinalIgnoreCase) &&
                                                string.Equals(m.Controller, item.Controller, StringComparison.OrdinalIgnoreCase) &&
                                                string.Equals(m.Action, item.Action, StringComparison.OrdinalIgnoreCase));
                }
                catch (InvalidOperationException)
                {
                    throw new OsharpException($"发现多个“{item.Area}-{item.Controller}-{item.Action}”的功能信息,不允许重名");
                }
                if (function == null)
                {
                    continue;
                }
                if (!string.Equals(item.Name, function.Name, StringComparison.OrdinalIgnoreCase))
                {
                    item.Name = function.Name;
                    isUpdate  = true;
                }
                if (item.IsAjax != function.IsAjax)
                {
                    item.IsAjax = function.IsAjax;
                    isUpdate    = true;
                }
                if (!item.IsAccessTypeChanged && item.AccessType != function.AccessType)
                {
                    item.AccessType = function.AccessType;
                    isUpdate        = true;
                }
                if (isUpdate)
                {
                    repository.Update(item);
                    updateCount++;
                }
            }
            repository.UnitOfWork.Commit();
            if (removeCount + addCount + updateCount > 0)
            {
                string msg = "刷新功能信息";
                if (addCount > 0)
                {
                    msg += ",添加功能信息 " + addCount + " 个";
                }
                if (updateCount > 0)
                {
                    msg += ",更新功能信息 " + updateCount + " 个";
                }
                if (removeCount > 0)
                {
                    msg += ",移除功能信息 " + removeCount + " 个";
                }
                Logger.LogInformation(msg);
            }
        }
示例#5
0
        /// <summary>
        /// 将从程序集获取的实体信息同步到数据库
        /// </summary>
        protected virtual void SyncToDatabase(IServiceProvider scopedProvider, List <TEntityInfo> entityInfos)
        {
            IRepository <TEntityInfo, Guid> repository = scopedProvider.GetService <IRepository <TEntityInfo, Guid> >();

            if (repository == null)
            {
                _logger.LogWarning("初始化实体数据时,IRepository<,>的服务未找到,请初始化 EntityFrameworkCoreModule 模块");
                return;
            }

            //检查指定实体的Hash值,决定是否需要进行数据库同步
            if (!entityInfos.CheckSyncByHash(scopedProvider, _logger))
            {
                _logger.LogInformation("同步实体数据时,数据签名与上次相同,取消同步");
                return;
            }

            TEntityInfo[] dbItems = repository.Query(null, false).ToArray();

            //删除的实体信息
            TEntityInfo[] removeItems = dbItems.Except(entityInfos, EqualityHelper <TEntityInfo> .CreateComparer(m => m.TypeName)).ToArray();
            int           removeCount = removeItems.Length;

            //todo:由于外键关联不能物理删除的实体,需要实现逻辑删除
            repository.Delete(removeItems);

            //处理新增的实体信息
            TEntityInfo[] addItems = entityInfos.Except(dbItems, EqualityHelper <TEntityInfo> .CreateComparer(m => m.TypeName)).ToArray();
            int           addCount = addItems.Length;

            repository.Insert(addItems);

            //处理更新的实体信息
            int updateCount = 0;

            foreach (TEntityInfo item in dbItems.Except(removeItems))
            {
                bool        isUpdate   = false;
                TEntityInfo entityInfo = entityInfos.SingleOrDefault(m => m.TypeName == item.TypeName);
                if (entityInfo == null)
                {
                    continue;
                }

                if (item.Name != entityInfo.Name)
                {
                    item.Name = entityInfo.Name;
                    isUpdate  = true;
                }

                if (item.PropertyJson != entityInfo.PropertyJson)
                {
                    item.PropertyJson = entityInfo.PropertyJson;
                    isUpdate          = true;
                }

                if (isUpdate)
                {
                    repository.Update(item);
                    updateCount++;
                }
            }

            repository.UnitOfWork.Commit();
            if (removeCount + addCount + updateCount > 0)
            {
                string msg = "刷新实体信息";
                if (addCount > 0)
                {
                    msg += $",添加实体信息 {addCount} 个";
                    _logger.LogInformation($"新增{addItems.Length}个数据实体:{addItems.Select(m => m.TypeName).ExpandAndToString()}");
                }

                if (removeCount > 0)
                {
                    msg += $",删除实体信息 {removeCount} 个";
                    _logger.LogInformation($"删除{removeItems.Length}个数据实体:{removeItems.Select(m => m.TypeName).ExpandAndToString()}");
                }

                if (updateCount > 0)
                {
                    msg += $",更新实体信息 {updateCount} 个";
                    _logger.LogInformation($"更新{updateCount}个数据实体");
                }

                _logger.LogInformation(msg);
            }
        }
示例#6
0
        /// <summary>
        /// 更新功能信息到数据库中
        /// </summary>
        /// <param name="functions">功能信息集合</param>
        protected virtual void UpdateToRepository(TFunction[] functions)
        {
            IRepository <TFunction, TKey> repository = ServiceProvider.GetService <IRepository <TFunction, TKey> >();

            TFunction[] items = repository.GetByPredicate(m => m.PlatformToken == PlatformToken).ToArray();

            //删除的功能(排除自定义功能信息)
            TFunction[] removeItems = items.Where(m => !m.IsCustom).Except(functions,
                                                                           EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action + m.PlatformToken)).ToArray();
            int removeCount = removeItems.Length;
            int tmpCount    = 0;

            foreach (TFunction removeItem in removeItems)
            {
                try
                {
                    tmpCount += repository.Delete(removeItem);
                }
                catch (Exception)
                {
                    //无法物理删除,可能是外键约束,改为逻辑删除
                    removeItem.IsDeleted = true;
                    tmpCount            += repository.Update(removeItem);
                }
            }
            if (tmpCount > 0)
            {
                items = repository.GetByPredicate(m => true).ToArray();
            }

            repository.UnitOfWork.TransactionEnabled = true;
            //处理新增的功能
            TFunction[] addItems = functions.Except(items,
                                                    EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action + m.PlatformToken)).ToArray();
            int addCount = addItems.Length;

            repository.Insert(addItems.AsEnumerable());

            //处理更新的功能
            int updateCount = 0;

            foreach (TFunction item in items)
            {
                if (item.IsCustom)
                {
                    continue;
                }
                bool      isUpdate = false;
                TFunction function = functions.SingleOrDefault(m => m.Area == item.Area && m.Controller == item.Controller &&
                                                               m.Action == item.Action && m.PlatformToken == PlatformToken);
                if (function == null)
                {
                    continue;
                }
                if (item.Name != function.Name)
                {
                    item.Name = function.Name;
                    isUpdate  = true;
                }
                if (item.IsAjax != function.IsAjax)
                {
                    item.IsAjax = function.IsAjax;
                    isUpdate    = true;
                }
                if (!item.IsTypeChanged && item.FunctionType != function.FunctionType)
                {
                    item.FunctionType = function.FunctionType;
                    isUpdate          = true;
                }
                if (isUpdate)
                {
                    repository.Update(item);
                    updateCount++;
                }
            }
            int count = repository.UnitOfWork.SaveChanges();

            if (removeCount > 0 || count > 0)
            {
                string message = "刷新功能信息";
                if (addCount > 0)
                {
                    message += ",添加功能信息 " + addCount + " 个";
                }
                if (updateCount > 0)
                {
                    message += ",更新功能信息 " + updateCount + " 个";
                }
                if (removeCount > 0)
                {
                    message += ",移除功能信息 " + removeCount + " 个";
                }
                Logger.Info(message);
            }
        }
        /// <summary>
        /// 更新实体信息到数据库中
        /// </summary>
        /// <param name="entityInfos">实体信息集合</param>
        protected virtual void UpdateToRepository(TEntityInfo[] entityInfos)
        {
            IRepository <TEntityInfo, TKey> repository = ServiceProvider.GetService <IRepository <TEntityInfo, TKey> >();

            TEntityInfo[] items = repository.TrackEntities.ToArray();

            //删除的实体信息
            TEntityInfo[] removeItems = items.Except(entityInfos,
                                                     EqualityHelper <TEntityInfo> .CreateComparer(m => m.ClassName)).ToArray();
            int removeCount = removeItems.Length;

            repository.UnitOfWork.BeginTransaction();
            int tmpCount = 0;

            foreach (TEntityInfo removeItem in removeItems)
            {
                try
                {
                    removeItem.IsDeleted = true;
                    tmpCount            += repository.Delete(removeItem);
                }
                catch (Exception)
                {
                    //无法物理删除,可能是外键约束,改为逻辑删除
                    tmpCount += repository.Recycle(removeItem);
                }
            }
            repository.UnitOfWork.Commit();
            if (tmpCount > 0)
            {
                items = repository.TrackEntities.ToArray();
            }

            repository.UnitOfWork.BeginTransaction();
            //处理新增的实体信息
            TEntityInfo[] addItems = entityInfos.Except(items,
                                                        EqualityHelper <TEntityInfo> .CreateComparer(m => m.ClassName)).ToArray();
            int addCount = addItems.Length;

            repository.Insert(addItems.AsEnumerable());

            //处理更新的实体信息
            int updateCount = 0;

            tmpCount = 0;
            foreach (TEntityInfo item in items)
            {
                bool        isUpdate   = false;
                TEntityInfo entityInfo = entityInfos.Single(m => m.ClassName == item.ClassName);
                if (item.Name != entityInfo.Name)
                {
                    item.Name = entityInfo.Name;
                    isUpdate  = true;
                }
                if (item.PropertyNamesJson != entityInfo.PropertyNamesJson)
                {
                    item.PropertyNamesJson = entityInfo.PropertyNamesJson;
                    isUpdate = true;
                }
                if (isUpdate)
                {
                    tmpCount += repository.Update(item);
                    updateCount++;
                }
            }
            repository.UnitOfWork.Commit();
            if (removeCount > 0 || tmpCount > 0)
            {
                string message = "刷新实体信息";
                if (addCount > 0)
                {
                    message += ",添加实体信息 " + addCount + " 个";
                }
                if (updateCount > 0)
                {
                    message += ",更新实体信息 " + updateCount + " 个";
                }
                if (removeCount > 0)
                {
                    message += ",移除实体信息 " + removeCount + " 个";
                }
                Logger.Info(message);
            }
        }
示例#8
0
        /// <summary>
        /// 更新实体信息到数据库中
        /// </summary>
        /// <param name="entityInfos">实体信息集合</param>
        protected virtual void UpdateToRepository(TEntityInfo[] entityInfos)
        {
            IRepository <TEntityInfo, TKey> repository = ServiceProvider.GetService <IRepository <TEntityInfo, TKey> >();

            TEntityInfo[] items = repository.GetByPredicate(m => true).ToArray();

            //删除的实体信息
            TEntityInfo[] removeItems = items.Except(entityInfos,
                                                     EqualityHelper <TEntityInfo> .CreateComparer(m => m.ClassName)).ToArray();
            int removeCount = removeItems.Length;

            if (repository.Delete(removeItems) > 0)
            {
                items = repository.GetByPredicate(m => true).ToArray();
            }

            repository.UnitOfWork.TransactionEnabled = true;
            //处理新增的实体信息
            TEntityInfo[] addItems = entityInfos.Except(items,
                                                        EqualityHelper <TEntityInfo> .CreateComparer(m => m.ClassName)).ToArray();
            int addCount = addItems.Length;

            repository.Insert(addItems.AsEnumerable());

            //处理更新的实体信息
            int updateCount = 0;

            foreach (TEntityInfo item in items)
            {
                bool        isUpdate   = false;
                TEntityInfo entityInfo = entityInfos.Single(m => m.ClassName == item.ClassName);
                if (item.Name != entityInfo.Name)
                {
                    item.Name = entityInfo.Name;
                    isUpdate  = true;
                }
                if (item.PropertyNamesJson != entityInfo.PropertyNamesJson)
                {
                    item.PropertyNamesJson = entityInfo.PropertyNamesJson;
                    isUpdate = true;
                }
                if (isUpdate)
                {
                    repository.Update(item);
                    updateCount++;
                }
            }
            int count = repository.UnitOfWork.SaveChanges();

            if (removeCount > 0 || count > 0)
            {
                string message = "刷新实体信息";
                if (addCount > 0)
                {
                    message += ",添加实体信息 " + addCount + " 个";
                }
                if (updateCount > 0)
                {
                    message += ",更新实体信息 " + updateCount + " 个";
                }
                if (removeCount > 0)
                {
                    message += ",移除实体信息 " + removeCount + " 个";
                }
                Logger.Info(message);
            }
        }
示例#9
0
        public IActionResult RoleFunctionMapSet(RoleFunctionSetDto dto)
        {
            AjaxResult result = new AjaxResult
            {
                Type    = Data.AjaxResultType.Success,
                Content = "操作成功:<br>"
            };
            int delCount = 0;
            int addCount = 0;

            //特殊处理
            if (dto.FunctionIds == null || dto.FunctionIds.Length == 0)
            {
                delCount = _roleFunctionMapContract.Delete(m => m.RoleId == dto.RoleId);
            }
            else
            {
                try
                {
                    var dbItem = _roleFunctionMapContract.Entities.Where(m => m.RoleId == dto.RoleId).ToArray();

                    int count             = dto.FunctionIds.Length;
                    RoleFunctionMap[] arr = new RoleFunctionMap[count];
                    for (int i = 0; i < count; i++)
                    {
                        arr[i] = new RoleFunctionMap
                        {
                            RoleId     = dto.RoleId,
                            FunctionId = dto.FunctionIds[i]
                        };
                    }

                    _roleFunctionMapContract.UnitOfWork.BeginTran();


                    //删除
                    var delItem = dbItem.Except(arr, EqualityHelper <RoleFunctionMap> .CreateComparer(m => m.RoleId + "-" + m.FunctionId)).ToArray();
                    if (delItem.Length > 0)
                    {
                        delCount = _roleFunctionMapContract.Delete(delItem.Select(m => m.Id).ToArray());
                    }

                    //新增
                    var addItem = arr.Except(dbItem, EqualityHelper <RoleFunctionMap> .CreateComparer(m => m.RoleId + "-" + m.FunctionId)).ToArray();
                    if (addItem.Length > 0)
                    {
                        addCount = _roleFunctionMapContract.Insert(addItem);
                    }

                    _roleFunctionMapContract.UnitOfWork.Commit();
                }
                catch (Exception)
                {
                    _roleFunctionMapContract.UnitOfWork.Rollback();
                }
            }

            if (addCount > 0)
            {
                result.Content += "新增 " + addCount + " 条权限<br>";
            }
            if (delCount > 0)
            {
                result.Content += "删除 " + delCount + " 条权限<br>";
            }
            if (addCount == 0 && delCount == 0)
            {
                result.Content += "无任何修改!";
            }
            else
            {
                //同步到缓存
                _roleFunctionMapContract.SyncToCache(dto.RoleId);
            }

            return(Json(result));
        }
示例#10
0
        /// <summary>
        /// 将从程序集获取的实体信息同步到数据库
        /// </summary>
        protected virtual void SyncToDatabase(IServiceProvider scopedProvider, List <TEntityInfo> entityInfos)
        {
            IRepository <TEntityInfo, Guid> repository = scopedProvider.GetService <IRepository <TEntityInfo, Guid> >();

            if (repository == null)
            {
                throw new OsharpException("IRepository<,>的服务未找到,请初始化 EntityFrameworkCoreModule 模块");
            }
            TEntityInfo[] dbItems = repository.TrackEntities.ToArray();

            //删除的实体信息
            TEntityInfo[] removeItems = dbItems.Except(entityInfos, EqualityHelper <TEntityInfo> .CreateComparer(m => m.TypeName)).ToArray();
            int           removeCount = removeItems.Length;

            //todo:由于外键关联不能物理删除的实体,需要实现逻辑删除
            repository.Delete(removeItems);

            //处理新增的实体信息
            TEntityInfo[] addItems = entityInfos.Except(dbItems, EqualityHelper <TEntityInfo> .CreateComparer(m => m.TypeName)).ToArray();
            int           addCount = addItems.Length;

            repository.Insert(addItems);

            //处理更新的实体信息
            int updateCount = 0;

            foreach (TEntityInfo item in dbItems.Except(removeItems))
            {
                bool        isUpdate   = false;
                TEntityInfo entityInfo = entityInfos.SingleOrDefault(m => m.TypeName == item.TypeName);
                if (entityInfo == null)
                {
                    continue;
                }
                if (item.Name != entityInfo.Name)
                {
                    item.Name = entityInfo.Name;
                    isUpdate  = true;
                }
                if (item.PropertyNamesJson != entityInfo.PropertyNamesJson)
                {
                    item.PropertyNamesJson = entityInfo.PropertyNamesJson;
                    isUpdate = true;
                }
                if (isUpdate)
                {
                    repository.Update(item);
                    updateCount++;
                }
            }
            repository.UnitOfWork.Commit();
            if (removeCount + addCount + updateCount > 0)
            {
                string msg = "刷新实体信息";
                if (addCount > 0)
                {
                    msg += $",添加实体信息 {addCount} 个";
                }
                if (updateCount > 0)
                {
                    msg += $",更新实体信息 {updateCount} 个";
                }
                if (removeCount > 0)
                {
                    msg += $",删除实体信息 {removeCount} 个";
                }
                _logger.LogInformation(msg);
            }
        }
示例#11
0
        /// <summary>
        /// 更新功能信息到数据库中
        /// </summary>
        /// <param name="functions">功能信息集合</param>
        protected virtual void UpdateToRepository(TFunction[] functions)
        {
            if (functions.Length == 0)
            {
                return;
            }
            IRepository <TFunction, TKey> repository = ServiceProvider.GetService <IRepository <TFunction, TKey> >();

            if (repository == null)
            {
                return;
            }
            TFunction[] items = repository.TrackEntities.Where(m => m.PlatformToken == PlatformToken).ToArray();

            //删除的功能(排除自定义功能信息)
            TFunction[] removeItems = items.Where(m => !m.IsCustom).Except(functions,
                                                                           EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action + m.PlatformToken)).ToArray();
            int removeCount = removeItems.Length;

            repository.UnitOfWork.BeginTransaction();
            int tmpCount = 0;

            foreach (TFunction removeItem in removeItems)
            {
                try
                {
                    removeItem.IsDeleted = true;
                    tmpCount            += repository.Delete(removeItem);
                }
                catch (Exception)
                {
                    //无法物理删除,可能是外键约束,改为逻辑删除
                    tmpCount += repository.Recycle(removeItem);
                }
            }
            repository.UnitOfWork.Commit();
            if (tmpCount > 0)
            {
                items = repository.TrackEntities.ToArray();
            }

            repository.UnitOfWork.BeginTransaction();
            //处理新增的功能
            TFunction[] addItems = functions.Except(items,
                                                    EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action + m.PlatformToken)).ToArray();
            int addCount = addItems.Length;

            repository.Insert(addItems.AsEnumerable());

            //处理更新的功能
            int updateCount = 0;

            tmpCount = 0;
            foreach (TFunction item in items)
            {
                if (item.IsCustom)
                {
                    continue;
                }
                bool      isUpdate = false;
                TFunction function = functions.SingleOrDefault(m =>
                                                               string.Equals(m.Area, item.Area, StringComparison.OrdinalIgnoreCase) &&
                                                               string.Equals(m.Controller, item.Controller, StringComparison.OrdinalIgnoreCase) &&
                                                               string.Equals(m.Action, item.Action, StringComparison.OrdinalIgnoreCase) &&
                                                               m.PlatformToken == PlatformToken);
                if (function == null)
                {
                    continue;
                }
                if (!item.Name.Equals(function.Name, StringComparison.OrdinalIgnoreCase))
                {
                    item.Name = function.Name;
                    isUpdate  = true;
                }
                if (item.IsAjax != function.IsAjax)
                {
                    item.IsAjax = function.IsAjax;
                    isUpdate    = true;
                }
                if (!item.IsTypeChanged && item.FunctionType != function.FunctionType)
                {
                    item.FunctionType = function.FunctionType;
                    isUpdate          = true;
                }
                if (isUpdate)
                {
                    tmpCount += repository.Update(item);
                    updateCount++;
                }
            }
            repository.UnitOfWork.Commit();
            if (removeCount > 0 || tmpCount > 0)
            {
                string message = "刷新功能信息";
                if (addCount > 0)
                {
                    message += ",添加功能信息 " + addCount + " 个";
                }
                if (updateCount > 0)
                {
                    message += ",更新功能信息 " + updateCount + " 个";
                }
                if (removeCount > 0)
                {
                    message += ",移除功能信息 " + removeCount + " 个";
                }
                Logger.Info(message);
            }
        }
        /// <summary>
        /// 将从程序集获取的功能信息同步到数据库中
        /// </summary>
        /// <param name="scopedProvider">局部服务程序提供者</param>
        /// <param name="functions">程序集获取的功能信息</param>
        protected virtual void SyncToDatabase(IServiceProvider scopedProvider, Function[] functions)
        {
            Check.NotNull(functions, nameof(functions));
            if (functions.Length == 0)
            {
                return;
            }

            IRepository <Function, int> repository = scopedProvider.GetService <IRepository <Function, int> >();

            if (repository == null)
            {
                Logger.LogWarning("初始化功能数据时,IRepository<,>的服务未找到");
                return;
            }
            repository.UnitOfWork.BeginTran();

            try
            {
                var        app     = options.LocalOption.AppKey;
                Function[] dbItems = repository.Entities.Where(m => m.Source == app).ToArray();

                //删除的功能
                Function[] removeItems = dbItems.Except(functions,
                                                        EqualityHelper <Function> .CreateComparer(m => m.IsWebApi.ToString() + m.Area + m.Controller + m.Action)).ToArray();
                int removeCount = removeItems.Length;
                if (removeCount > 0)
                {
                    repository.Delete(removeItems.Select(m => m.Id).ToArray());
                }


                //新增的功能
                Function[] addItems = functions.Except(dbItems,
                                                       EqualityHelper <Function> .CreateComparer(m => m.IsWebApi.ToString() + m.Area + m.Controller + m.Action)).ToArray();
                int addCount = addItems.Length;
                if (addCount > 0)
                {
                    repository.Insert(addItems);
                }


                //更新的功能信息
                int        updateCount = 0;
                Function[] updateItems = dbItems.Except(removeItems).ToArray();
                foreach (Function item in updateItems)
                {
                    bool     isUpdate = false;
                    Function function;
                    try
                    {
                        function = functions.Single(m =>
                                                    m.IsWebApi == item.IsWebApi &&
                                                    string.Equals(m.Area, item.Area, StringComparison.OrdinalIgnoreCase) &&
                                                    string.Equals(m.Controller, item.Controller, StringComparison.OrdinalIgnoreCase) &&
                                                    string.Equals(m.Action, item.Action, StringComparison.OrdinalIgnoreCase));
                    }
                    catch (InvalidOperationException)
                    {
                        throw new TomNetException($"发现多个“{item.Area}-{item.Controller}-{item.Action}”的功能信息,不允许重名");
                    }
                    if (function == null)
                    {
                        continue;
                    }
                    if (!string.Equals(item.Name, function.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        item.Name = function.Name;
                        isUpdate  = true;
                    }

                    if (item.AccessType != function.AccessType)
                    {
                        item.AccessType = function.AccessType;
                        isUpdate        = true;
                    }
                    if (isUpdate)
                    {
                        repository.Update(item);
                        updateCount++;
                        Logger.LogDebug($"更新功能“{function.Name}({function.Area}/{function.Controller}/{function.Action})”");
                    }
                }
                repository.UnitOfWork.Commit();
                if (removeCount + addCount + updateCount > 0)
                {
                    string msg = "刷新功能信息";
                    if (addCount > 0)
                    {
                        foreach (Function function in addItems)
                        {
                            Logger.LogDebug($"新增功能“{function.Name}({function.Area}/{function.Controller}/{function.Action})”");
                        }
                        msg += ",添加功能信息 " + addCount + " 个";
                    }
                    if (updateCount > 0)
                    {
                        msg += ",更新功能信息 " + updateCount + " 个";
                    }
                    if (removeCount > 0)
                    {
                        foreach (Function function in removeItems)
                        {
                            Logger.LogDebug($"更新功能“{function.Name}({function.Area}/{function.Controller}/{function.Action})”");
                        }
                        msg += ",移除功能信息 " + removeCount + " 个";
                    }
                    Logger.LogInformation(msg);
                }
            }
            catch (Exception ex)
            {
                repository.UnitOfWork.Rollback();
                Logger.LogError(ex.Message);
            }
        }
示例#13
0
        /// <summary>
        /// 将从程序集获取的功能信息同步到数据库中
        /// </summary>
        /// <param name="functions">程序集获取的功能信息</param>
        protected virtual void SyncToDatabase(TFunction[] functions)
        {
            Check.NotNull(functions, nameof(functions));
            if (functions.Length == 0)
            {
                return;
            }

            IRepository <TFunction, Guid> repository = ScopedServiceProvider.GetService <IRepository <TFunction, Guid> >();

            if (repository == null)
            {
                return;
            }
            TFunction[] dbItems = repository.TrackQuery().ToArray();

            //删除的功能
            TFunction[] removeItems = dbItems.Except(functions,
                                                     EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action)).ToArray();
            int removeCount = removeItems.Length;

            //todo:由于外键关联不能物理删除的实体,需要实现逻辑删除
            repository.Delete(removeItems);

            //新增的功能
            TFunction[] addItems = functions.Except(dbItems,
                                                    EqualityHelper <TFunction> .CreateComparer(m => m.Area + m.Controller + m.Action)).ToArray();
            int addCount = addItems.Length;

            repository.Insert(addItems);

            //更新的功能信息
            int updateCount = 0;

            foreach (TFunction item in dbItems.Except(removeItems))
            {
                bool      isUpdate = false;
                TFunction function = functions.Single(m => m.Area == item.Area && m.Controller == item.Controller && m.Action == item.Action);
                if (function == null)
                {
                    continue;
                }
                if (item.Name != function.Name)
                {
                    item.Name = function.Name;
                    isUpdate  = true;
                }
                if (item.IsAjax != function.IsAjax)
                {
                    item.IsAjax = function.IsAjax;
                    isUpdate    = true;
                }
                if (!item.IsAccessTypeChanged && item.AccessType != function.AccessType)
                {
                    item.AccessType = function.AccessType;
                    isUpdate        = true;
                }
                if (isUpdate)
                {
                    repository.Update(item);
                    updateCount++;
                }
            }
            repository.UnitOfWork.Commit();
            if (removeCount + addCount + updateCount > 0)
            {
                string msg = "刷新功能信息";
                if (addCount > 0)
                {
                    msg += ",添加功能信息 " + addCount + " 个";
                }
                if (updateCount > 0)
                {
                    msg += ",更新功能信息 " + updateCount + " 个";
                }
                if (removeCount > 0)
                {
                    msg += ",移除功能信息 " + removeCount + " 个";
                }
                _logger.LogInformation(msg);
            }
        }