Dapper and anonymous Types

前端 未结 3 1802
刺人心
刺人心 2020-12-08 07:38

Is it possible to use anonymous types with Dapper?

I can see how you can use dynamic i.e.

connection.Query(blah, blah, blah) 
         


        
相关标签:
3条回答
  • 2020-12-08 07:53

    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);
    }
    
    0 讨论(0)
  • 2020-12-08 07:54

    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.

    0 讨论(0)
  • 2020-12-08 08:17

    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");
    
    0 讨论(0)
提交回复
热议问题