How to return dynamic values in C# Dapper?

dapper

Question

I am trying to obtain values from a query that returns dynamic data, but I am unable to do it using Dapper as instructed in their instructions (https://github.com/StackExchange/Dapper).

There is an example of their code here:

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

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

However, no matter what I do, I am unable to access any of the members of the returned information:

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!!

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

Where do I find my fields?

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

Accepted Answer

The solution is to do something like this. You must first add the query's return type to dynamic before casting each row into anIDictionary<string, object> . After doing so, you'll be able to get the value for your key-based query like follows:

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 wish it could aid 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