ASP核心-树状结构-映射

时间:2020-05-25 15:40:19

标签: c# asp.net asp.net-core

我正在创建一个树结构,其中有节点和叶子。每个节点都有子节点和子叶子。

以下是实体的结构:

节点:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace TreeWithReact.Entities
{
    public class Node
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int NodeId { get; private set; }
        public string Name { get; set; }
        public int? ParentNodeId { get; set; }
        [ForeignKey("ParentNodeId")]
        public Node ParentNode { get; set; }
        public List<Node> SubNodes { get; set; }
        public List<Leaf> SubLeaves { get; set; }
        public Node()
        {
            SubNodes = new List<Node>();
            SubLeaves = new List<Leaf>();
        }
    }
}

叶子:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace TreeWithReact.Entities
{
    public class Leaf
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int LeafId { get; set; }
        public string Name { get; set; }
        public int? ParentNodeId { get; set; }
        [ForeignKey("ParentNodeId")]
        public Node ParentNode { get; set; }
    }
}

和关系:

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Node>()
                .HasMany(cat => cat.SubNodes)
                .WithOne(cat => cat.ParentNode);

            modelBuilder.Entity<Node>()
                .HasMany(cat => cat.SubLeaves)
                .WithOne(cat => cat.ParentNode);
        }

这是负责获取整棵树的方法:

        public async Task<IEnumerable<NodeModel>> GetTreeAsync()
        {
            var nodes = await _context.Nodes.ToListAsync();

            return _mapper.Map<IEnumerable<NodeModel>>(nodes);
        }

节点已映射到NodeModel:

    public class NodeModel
    {
        public string Name { get; set; }
        public List<NodeModel> SubNodes { get; set; }
        public List<LeafModel> SubLeaves { get; set; }
    }
}

这是AutoMapper配置:

            CreateMap<Node, NodeModel>()
                .ForMember(dest => dest.SubLeaves, opt => opt.MapFrom<IEnumerable<Leaf>>(src => src.SubLeaves));

但是结果是,我收到一个空的SubLeaves数组,SubNodes正确显示。我不知道onModelCreating中的某些问题是错误的。

1 个答案:

答案 0 :(得分:0)

好吧,我忘记添加Include来获取Nodes方法列表。而且不需要映射器ForMember方法。

extension IterableExtensions<T> on Iterable<T> {

  Iterable<T> sortBy<TSelected extends Comparable<TSelected>>(
      TSelected Function(T) selector) =>
  toList()..sort((a, b) => selector(a).compareTo(selector(b)));

  Iterable<T> sortByDescending<TSelected extends Comparable<TSelected>>(
      TSelected Function(T) selector) =>
  sortBy(selector).toList().reversed;

}