using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace Infrastructure.Domain { public abstract class BaseTreeEntity : BaseEntity where T : BaseTreeEntity { [Display(Name = "名称")] public string Name { get; set; } [Display(Name = "编号")] public string Number { get; set; } [Display(Name = "路径")] public string Path { get; set; } [Display(Name = "上级Id")] public Guid? ParentId { get; set; } public T Parent { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "CA2227:集合属性应为只读", Justification = "<挂起>")] public List Children { get; set; } = new List(); public string GetFullName(string separator = "→") { var names = new List(); var item = this; while (item != null) { names.Add(item.Name); if (item.Parent == null || item.Parent.Id == this.Id) { break; } item = item.Parent; } names.Reverse(); return string.Join(separator, names); } public void UpdatePath() { var paths = new List(); var current = this; while (true) { paths.Add(current.Number); if (current.Parent != null) { current = current.Parent; } else { break; } } paths.Reverse(); this.Path = string.Join("/", paths.ToArray()); if (this.Children.Any()) { foreach (var item in this.Children) { item.UpdatePath(); } } } } }