【问题标题】:Dapper Build Object Tree Containing Same Object TypeDapper 构建包含相同对象类型的对象树
【发布时间】:2017-03-10 00:28:42
【问题描述】:

我有一个表来表达类别之间可能的父子关系。根类别不包含 ParentId 值,而是 null。我觉得也有必要指出它应该构建N级深度。

例如考虑下面的 Sql 表。

类别: 身份证 |姓名 |父母身份

其中 ParentId 是与同一个表的 Id 列的关系。

想了解是否可以填充以下类?

public class Category
{
    public string Id
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }

    public List<Category> Categories
    {
        get;
        set;
    }
}

来自一个方法,例如:

public List<Category> GetCategories()
{
        // construct using dapper.
}

【问题讨论】:

    标签: dapper


    【解决方案1】:

    您可以从 DB 中获取平面列表并在 C# 中组装:

    [TestFixture]
    public class Recursion
    {
        [Test]
        public void Test()
        {
            using (var conn = new SqlConnection(@"Data Source=.\sqlexpress;Integrated Security=true; Initial Catalog=foo"))
            {
                var flatResult = conn.Query<Category>(@"select '1' as Id, 'Cat 1' as Name, ParentId = null 
                                                        union all select '2' as Id, 'Cat 2' as Name, '1' as ParentId 
                                                        union all select '3' as Id, 'Cat 3' as Name, '2' as ParentId
                                                        union all select '4' as Id, 'Cat 4' as Name, null as ParentId
                                                        union all select '5' as Id, 'Cat 5' as Name, 4 as ParentId");
                var tree = BuildTree(flatResult.ToList());
            }
        }
    
        private static IEnumerable<Category> BuildTree(List<Category> items)
        {
            items.ForEach(i => i.Categories = items.Where(ch => ch.ParentId == i.Id).ToList());
            return items.Where(i => i.ParentId == null).ToList();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2015-11-09
      相关资源
      最近更新 更多