根据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);但是,如果您必须知道字段名称和字段的数据类型,那么dynamic的用途是什么。如果我有:
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,并且是类型,例如Int 32
result[0].["Id"].Type --- what datattype is the value returned
result[0].["Description"]它将给出结果"This is the description“,类型为string。
我看到有一个results.table,它有一个带有字段名数组的dapperrow对象,还有一个result.values,它是一个包含值的object2,但它不能被访问。如果我在向下钻取的列名中添加一个监视,我就可以获得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.Items.table.FieldNames并拿回"Id“。
发布于 2014-11-15 00:05:45
您可以将每一行转换为一个IDictionary<string, object>,它应该提供对名称和值的访问。我们目前没有显式地跟踪类型--我们根本没有必要这样做。如果这还不够,可以考虑使用返回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);
}
}https://stackoverflow.com/questions/26932789
复制相似问题