Cast dynamic dapper query

c# dapper

Question

Im trying to convert a dynamic query from dapper to 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
        }

But the cast always return null. Any clue?

Accepted Answer

You need to cast the individual rows as 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"]
    }

Popular Answer

Use "Cast<>":

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


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why