Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper - how to work with dynamic objects

Tags:

c#

dynamic

dapper

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?

like image 448
cogumel0 Avatar asked Nov 05 '13 16:11

cogumel0


People also ask

What is dynamic parameters in dapper?

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.

How do you make an object dynamic?

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.

Is Dapper a micro ORM?

This site is for developers who want to learn how to use Dapper - the micro ORM produced by the people behind Stack Overflow.

Is Dapper A ORM?

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.


1 Answers

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();
like image 174
Marc Gravell Avatar answered Oct 06 '22 03:10

Marc Gravell