//todo: not allow modify children public async override Task <TEntity> UpdateAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default) { var oldEntity = await this.FindAsync(entity.Id); if (oldEntity.ParentId == entity.Id) { await base.UpdateAsync(entity, autoSave, cancellationToken); return(entity); } var parentId = entity.ParentId; //Should find children before Code change var children = await FindChildrenAsync(entity.Id, true); //Store old code of Tree var oldCode = oldEntity.Code; //Move Tree var code = await GetNextChildCodeAsync(parentId); entity.SetCode(code); //Update Children Codes foreach (var child in children) { var childCode = TreeCodeGenerator.AppendCode(entity.Code, TreeCodeGenerator.GetRelativeCode(child.Code, oldCode)); child.SetCode(childCode); } await base.UpdateAsync(entity, autoSave, cancellationToken); return(entity); }
protected virtual async Task <string> GetNextChildCodeAsync(Guid?parentId) { var lastChild = await GetLastChildOrNullAsync(parentId); if (lastChild == null) { var parentCode = parentId != null ? await GetCodeAsync(parentId.Value) : null; return(TreeCodeGenerator.AppendCode(parentCode, TreeCodeGenerator.CreateCode(1))); } return(TreeCodeGenerator.CalculateNextCode(lastChild.Code)); }
private async Task traverseTreeAsync(TEntity parent, ICollection <TEntity> children, bool autoSave = false, CancellationToken cancellationToken = default) { if (children == null || !children.Any()) { return; } var index = 0; foreach (var c in children) { var code = TreeCodeGenerator.AppendCode(parent.Code, TreeCodeGenerator.CreateCode(++index)); c.SetCode(code); TraverseTreeAction?.Invoke(c); await traverseTreeAsync(c, c.Children, autoSave, cancellationToken); } }