Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper: How to read into list of Dictionary from query?

Dapper provides lots of ways mapping data into list of dynamic objects. However in some case I'd like to read data to list of Dictionary.

The SQL may looks like:

"SELECT * FROM tb_User"

As tb_User may change outside, I don't know what columns will return in result. So I can write some code like this:

var listOfDict = conn.QueryAsDictionary(sql);
foreach (var dict in listOfDict) {
    if (dict.Contains("anyColumn")) {
        // do right thing...
    }
}

Is there any built-in methods for Dapper to do this conversion?

like image 964
ineztia Avatar asked Mar 21 '16 13:03

ineztia


1 Answers

You can cast each row as IDictionary:

    var row = (IDictionary<string, object>)conn.Query("select foo = 1, bar = 'bar'").First();

    Assert.That(row["foo"], Is.EqualTo(1));
    Assert.That(row["bar"], Is.EqualTo("bar"));
like image 184
Void Ray Avatar answered Sep 17 '22 12:09

Void Ray