Is it possible to use anonymous types with Dapper?
I can see how you can use dynamic i.e.
connection.Query(blah, blah, blah)
Just a small improvement of Guillaume86's great solution:
public static IEnumerable<T> Query<T>(this IDbConnection connection, Func<T> typeBuilder,
string sql, dynamic param = null, IDbTransaction transaction = null,
bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
return SqlMapper.Query<T>(connection, sql, param, transaction, buffered,
commandTimeout, commandType);
}
Is it possible to use anonymous types with Dapper?
Sure see the non-generic Query override, it return a dynamic IDictionary<string, object>
this object is an expando that can either be cast or accessed with dot notation.
Eg:
var v = connection.Query("select 1 as a, 2 as b").First();
Console.Write("{0} {1}",v.a, v.b) // prints: 1 2
is it then possible to do a
.Select
Sure, you get an IEnumerable<dynamic>
... you can run anything you want on that.
Here's another solution to use anonymous types with dapper:
public static class DapperExtensions
{
public static IEnumerable<T> Query<T>(this IDbConnection connection, Func<T> typeBuilder, string sql)
{
return connection.Query<T>(sql);
}
}
and use it like this:
var data = connection.Query(() => new
{
ContactId = default(int),
Name = default(string),
}, "SELECT ContactId, Name FROM Contact");