How to use Dapper to return a list of dynamic types (list)?

.net c# dapper orm


I have been using for a while now and its a very good ORM mapper which works great with .Net dynamic types.

But I noticed that when Dapper retrieves data from a database it returns as DapperRow type.

Is there are any way that I can return it in any other type Like System.Dynamic.ExpandoObject?

5/30/2019 6:43:50 AM

Accepted Answer

The DapperRow object is designed to share a lot of state between rows. For example, if you fetch 40 rows, the column names etc are only stored once. If we used ExpandoObject, this would need to be configured per row. Hence, the use of DapperRow as the behind-the-scenes implementation detail is a deliberate efficiency thing.

Note that the object returned from the dynamic APIs can also be cast as IDictionary<string,object>.

I would, however, be open to supporting other types that support this dictionary usage - of which ExpandoObject is one. So yes, it could be changed such that:

var rows = conn.Query<ExpandoObject>(...);

works. It simply requires code to support it, and that code does not currently exist. So "no, but perhaps in a future build".

Note also that you don't need to use DapperRow at all... The more expected scenario is to use the generic API to materialize your own types.

5/30/2019 6:45:18 AM

Popular Answer


As per dapper documentation use the query method and get your dymanics:

dynamic account = conn.Query<dynamic>(@"
                    SELECT Name, Address, Country
                    FROM Account
            WHERE Id = @Id", new { Id = Id }).FirstOrDefault();

As you can see you get a dynamic object and you can access its properties as long as they are well defined in the query statement.

If you omit .FirstOrDefault() you get an IEnumerable<dynamic> which you can do whatever you want with it.

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