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?
The DynamicParameters type provides an Add method, enabling you to pass explicit parameters, specifying the datatype, direction and size: var parameters = new DynamicParameters(); var customerId = "ALFKI"; parameters. Add("@CustomerId", customerId, DbType.
You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.
This site is for developers who want to learn how to use Dapper - the micro ORM produced by the people behind Stack Overflow.
Dapper is an object–relational mapping (ORM) product for the Microsoft . NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With