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

标签 dapper

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

例如,考虑以下 Sql 表。

类别: 身份证 |名称 |父级 ID

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

最佳答案

您可以从数据库获取平面列表并用 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 构建包含相同对象类型的对象树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42689413/

相关文章:

c# - Dapper 参数不能通过 npgsql 连接与 PostgreSQL 一起使用,是否支持 postgres 匿名函数参数化?

c# - Dapper 的通用存储库

c# - 如何将 ormlite 与 SQL Server 和 Mars 一起使用?

c# - 如何在小巧玲珑中返回原始数据类型的元组

azure-sql-database - 如何为 Dapper 实现 SQL Azure transient 故障处理框架?

sql-server - Dapper:无法解析 float (解析列时出错)

c# - Dapper 可以返回映射对象和其他非映射值吗?

c# - 关于如何将 Dapper 与 Structuremap 和依赖注入(inject)一起使用的简单但很好的示例

asp.net-mvc-3 - 用于检索的 Dapper 和用于 CRUD 的 NHibernate 是否适用于 Web 应用程序

c# - Dapper.Contrib - InsertAsync 无法插入 HIERARCHYID 键