Ejemplo n.º 1
0
        public async Task AddAsync(OrganizationTree entity)
        {
            if (string.IsNullOrWhiteSpace(entity.ParentObjId))
            {
                entity.SetLValue(1);
                entity.SetRValue(2);
                entity.SetGroup(GuidGen.NewGUID());
            }
            else
            {
                var parentNode = _context.Set <OrganizationTree>().FirstOrDefault(x => x.ObjId == entity.ParentObjId);
                if (parentNode == null)
                {
                    throw new Exception($"找不到ObjId为{entity.ParentObjId}的上级节点");
                }
                var referenceNodes = _context.Set <OrganizationTree>().Where(x => x.Group == parentNode.Group).ToList();
                //新节点
                entity.SetLValue(parentNode.RValue);
                entity.SetRValue(parentNode.RValue + 1);
                entity.SetGroup(parentNode.Group);
                entity.SetParentId(parentNode.Id);
                for (int idx = referenceNodes.Count - 1; idx >= 0; idx--)
                {
                    var node = referenceNodes[idx];
                    //1.父节点
                    //只是右值加2
                    if (node.Id == parentNode.Id)
                    {
                        node.SetRValue(node.RValue + 2);
                        continue;
                    }

                    //2.顶级节点
                    //只是右值加2
                    if (node.LValue == 1)
                    {
                        node.SetRValue(node.RValue + 2);
                        continue;
                    }

                    //3.沿线节点
                    //左右值都加2
                    if (node.LValue > parentNode.LValue && node.RValue > parentNode.RValue)
                    {
                        node.SetLValue(node.LValue + 2);
                        node.SetRValue(node.RValue + 2);
                        continue;
                    }
                }
                _context.Set <OrganizationTree>().UpdateRange(referenceNodes);
            }
            _context.Set <OrganizationTree>().Add(entity);
            await _context.SaveEntitiesAsync();
        }