Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast dynamic dapper query

Tags:

c#

dapper

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?

like image 557
Nils Anders Avatar asked Feb 11 '23 20:02

Nils Anders


1 Answers

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"]
    }
like image 57
rossipedia Avatar answered Feb 16 '23 03:02

rossipedia