如何在dapper中映射自引用表?

时间:2018-07-02 19:23:52

标签: asp.net .net-core dapper

我有一个在Id和ParentId之间具有自引用的表,这是我的模型

  public class Category
{
    public Category()
    {
        Children = new List<Category>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
    public IList<Category> Children { get; set; }
}

这是我的查询和映射

  string query = "SELECT * FROM Categories as A" +
                 " inner join Categories as B" +
                 " on A.Id = B.ParentId";
            var catDictionary = new Dictionary<int, Category>();
            var list = dbConnection.Query<Category, Category, Category>(query,
               (category, child) =>
               {
                   category.Children = category.Children ?? new List<Category>();
                   category.Children.Add(child);
                   return category;
               }).ToList();
                return list;

这是结果

节点重复且深度不完整

0 个答案:

没有答案