本文介绍了包含相同对象类型的Dapper构建对象树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,表示类别之间可能存在的父子关系。根类别将不包含ParentId值,而应为null。我认为还必须指出,它应该构造N级深度。

I have a single table which expresses a possible parent child relationship between Categories. Root categories would not contain a ParentId value, rather null. I think it's also important to point out that it should construct N level of depth.

例如,考虑以下Sql表。

For example consider the following Sql table.

类别:
ID |姓名| ParentId

Category :Id | Name | ParentId

其中ParentId是返回到同一表的ID列的关系。

Where ParentId is a relationship back to the Id column of the same table.

试图了解是否

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


推荐答案

您可以得到一个简单列表从DB并在C#中进行汇编:

You can get a flat list from DB and assemble in 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();
    }
}

这篇关于包含相同对象类型的Dapper构建对象树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 17:14