投射动态精巧的查询

时间:2015-02-25 07:55:03

标签: c# dapper

我试图将动态查询从dapper转换为IDictionary

        const string sql = @"SELECT Name, Street FROM Contact";
        dynamic query = null;

        using (var cn = Connection)
        {
            query = cn.Query<dynamic>(sql);
        }

        var rows = query as IDictionary<string, object>;

        foreach (var row in rows)
        {
            // Getting values and objects
        }

但是演员总是返回null。任何线索?

2 个答案:

答案 0 :(得分:8)

您需要将各行投射为IDictionary<string, object>

    const string sql = @"SELECT Name, Street FROM Contact";
    IEnumerable<dynamic> results = null;

    using (var cn = Connection)
    {
        results = cn.Query<dynamic>(sql);
    }

    foreach (var row in results)
    {
         var fields = row as IDictionary<string, object>;
         // do something with fields["Name"] and fields["Street"]
    }

答案 1 :(得分:0)

使用“演员&lt;&gt;”:

query.Cast<IDictionary<string, object>>()