Dapper - how to work with dynamic objects

c# dapper dynamic

Question

I'm using Dapper to query from SQL and have a dynamic query as such:

var returns = conn.Query(dynamicQuery);

When I then cycle through the results, I would like to find out what the type of date I am handling is so I tried doing the following:

foreach (var result in results)
{
    MessageBox.Show(result.GetType().ToString());
}

But it always fails on the MessageBox with the error Cannot perform runtime binding on a null reference.

If I use this instead:

var returns = conn.Query<object>(dynamicQuery);

Then the command works, but it gives me a Dapper.SqlMapper+DapperRow object type.

How can I find the type of a dynamic variable?

Accepted Answer

With the dynamic api, it is expected that you know the shape in terms of columns, i.e.

foreach(dynamic row in query) {
    int id = row.Id;
    //...
}

However, each row also implements IDictionary<string, object> if things are less clear: so cast to that.

Alternatively, if (comments) you know there is a single cell of type date time:

var when = conn.Query<DateTime>(...).Single();


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