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

c# dapper dictionary sql

Question

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?

Accepted Answer

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"));

Popular Answer

You could use the Cast extension method from System.Linq

IEnumerable<IDictionary<string, object>> rows;
rows = connection.Query(sqlRequest).Cast<IDictionary<string, object>>();

foreach (var row in rows)
{
    var columnValue = row['columnName']; // returns the value of the column name
}


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