Dapper and anonymous Types

血红的双手。 提交于 2019-11-28 19:11:34

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");
Sam Saffron

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.

pistipanko

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);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!