Пример #1
0
        public async Task <BaseResponse> AddType(TypeAddViewModel req, string account)
        {
            //类型可以添加多个顶级类型
            string pathId = null, pathName = null;

            if (req.ParentId.HasValue && req.ParentId.Value != 0)
            {
                var parent = await _tr.FindAsync(req.ParentId.Value);

                if (parent == null)
                {
                    return(new BaseResponse {
                        Success = false, Message = "输入的父类型不存在"
                    });
                }
                if (parent.Status == TypeStatus.Leaf)
                {
                    return(new BaseResponse {
                        Success = false, Message = "数据节点下不能添加节点"
                    });
                }
                if (parent.ParentId == null)
                {
                    pathId   = parent.Id.ToString();
                    pathName = parent.TypeName;
                }
                else
                {
                    pathId   = $"{ parent.PathId}/{parent.Id}";
                    pathName = $"{parent.PathName}/{parent.TypeName}";
                }
            }
            else//顶级节点
            {
                if (req.Status == 1)      //不能直接添加数据节点
                {
                    return(new BaseResponse {
                        Success = false, Message = "数据节点必须添加在目录节点下"
                    });
                }
            }
            //检查是否重名
            var ret = await _tr.Find(a => a.ParentId == req.ParentId && a.TypeName == req.TypeName).FirstOrDefaultAsync();

            if (ret != null)
            {
                return(new BaseResponse {
                    Success = false, Message = "该节点下已存在相同类型名称"
                });
            }
            var tm = _mapper.Map <TypeModel>(req);

            try
            {
                tm.Create   = account;
                tm.PathId   = pathId;
                tm.PathName = pathName;
                await _tr.AddAsync(tm);

                _log.LogInformation($"{account}添加类型{tm.Id}->{tm.TypeName}成功");
                return(new HandleResponse <int> {
                    Success = true, Message = "添加类型成功", Key = tm.Id
                });
            }
            catch (Exception ex)
            {
                _log.LogError($"{account}添加类型{req.TypeName}失败,失败原因:{ex.Message}->{ex.StackTrace}->{ex.InnerException}");
                return(new BaseResponse {
                    Success = false, Message = "添加类型失败,请联系管理员"
                });
            }
        }