How to return dynamic values in C# Dapper?

dapper

Question

I have a query where I am returning dynamic data and am unable to retrieve the values through Dapper as listed in their documentation (https://github.com/StackExchange/Dapper).

They have a sample of code like so,

var rows = connection.Query("select 1 A, 2 B union all select 3, 4");

Assert.Equal(1, (int)rows[0].A);

Yet, when I do the following, I cannot access any of the members of the result of my query:

var query = db.Query("SELECT SUM(UserRating) as 'Sum', AVG(UserRating) as 'Average', COUNT(*) as 'Total' FROM ActivityLogs");

query.FirstOrDefault(); // {{DapperRow, Sum= '3', Average = '3', Total = '1'}}
var sum = query[0].Sum; // error!!

error CS0021: Cannot apply indexing with [] to an expression of type 'object'

How do I get to my fields?

1
4
7/9/2018 4:27:21 AM

Accepted Answer

The solution is to do something like this. You need to add the return type of the query to dynamic and then cast each row into an IDictionary<string, object>. Once you do that, you'll be able to get the value for your query by key like so:

IEnumerable<dynamic> query = db.Query<dynamic>("SELECT SUM(UserRating) as 'Sum', AVG(UserRating) as 'Average', COUNT(*) as 'Total' FROM ActivityLogs");
foreach (var rows in query)
{
    var fields = rows as IDictionary<string, object>;
    var sum = fields["Sum"];
    // ...
}

I hope it helps others!

3
7/9/2018 3:52:46 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow