Dapper构建包含相同对象类型的对象树

时间:2017-03-09 07:41:05

标签: dapper

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

例如,请考虑以下Sql表。

分类: Id |名称|的ParentId

其中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.
}

1 个答案:

答案 0 :(得分: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();
    }
}