【问题标题】:Dapper Results(Dapper Row) with Bracket Notation带有括号符号的 Dapper 结果(Dapper Row)
【发布时间】:2014-11-14 14:59:35
【问题描述】:

根据 Dapper 文档,您可以使用以下代码从 dapper 获取动态列表:

var rows = connection.Query("select 1 A, 2 B union all select 3, 4");

((int)rows[0].A)
   .IsEqualTo(1);

((int)rows[0].B)
   .IsEqualTo(2);

((int)rows[1].A)
   .IsEqualTo(3);

((int)rows[1].B)
    .IsEqualTo(4);

但是,如果您必须知道字段的字段名称和数据类型,那么动态的用途是什么。 如果我有:

var result = Db.Query("Select * from Data.Tables");

我希望能够做到以下几点: 获取返回的字段名称和数据类型的列表。

使用字段名称对其进行迭代并通过以下方式获取数据:

result.Fields
["Id", "Description"]

result[0].values
[1, "This is the description"]

这会让我得到

result[0].["Id"].Value

这将给出结果 1 并且类型为 e.g.诠释 32

result[0].["Id"].Type --- what datattype is the value returned

result[0].["Description"]

这将给出结果“这是描述”,并且是字符串类型。

我看到有一个 results[0].table 有一个带有字段名数组的 dapperrow 对象,还有一个 result.values 是一个包含值的对象 [2],但它不能被访问。如果我在向下钻取的列名称中添加一个手表,我可以获得 id。自动创建的手表是:

(new System.Collections.Generic.Mscorlib_CollectionDebugView<Dapper.SqlMapper.DapperRow>(result as System.Collections.Generic.List<Dapper.SqlMapper.DapperRow>)).Items[0].table.FieldNames[0]   "Id"    string

所以我应该能够得到 result[0].Items[0].table.FieldNames[0] 并得到“Id”。

【问题讨论】:

    标签: dapper


    【解决方案1】:

    您可以将每一行转换为IDictionary&lt;string, object&gt;,它应该提供对名称和的访问。我们目前没有明确地跟踪 types - 我们根本不需要。如果这还不够,请考虑使用返回 IDataReader 的 dapper 方法 - 这将提供对原始数据的访问,同时仍然允许方便的调用/参数化语法。

    例如:

    var rows = ...
    foreach(IDictionary<string, object> row in rows) {
        Console.WriteLine("row:");
        foreach(var pair in row) {
            Console.WriteLine("  {0} = {1}", pair.Key, pair.Value);
        }
    }
    

    【讨论】:

    • 我该怎么做。他们的问题是我事先不知道键是什么,所以我不能遍历行并转换字段名称(例如,Id、Description 作为字典键,因为我只能使用 result[0].Id 或结果[0].描述
    • 键和值在结果中。但它位于一个名为 DapperTable 的私有密封类中。与值相同
    • 对我有很大帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2020-03-14
    • 2016-09-11
    • 2021-05-13
    相关资源
    最近更新 更多