Dapper unlimited multi-mapping

c# dapper

Question

So I have a situation where I have to join (and map) more than 7 entities (which as far as I see is the current limitation of Dapper). This is what I've got so far (pseudo code):

using (var connection = new SqlConnection(_connectionString)) {
   IEnumerable<BigEntity> results = 
      connection.Query<BigEntity, Lookup1, Lookup2, ... around 10 of them>(sql, 
         (b, l1, l2, l3) => {
            // map and return here
         },
         splitOn: "split1, split2 ...");
}

Is there any way around this limitation ? Anyone faced this before ? Some Dapper extensions perhaps ?

Accepted Answer

Currently the only two ways that I know of to work around this is to

  • Create a POCO class with the fields you want and use your query like a table
  • Modify Dapper's source code to allow for more mappings.

Popular Answer

There is a merged PR on this topic from Sep 2014:

https://github.com/StackExchange/Dapper/pull/158/files

The PR added methods where you can pass an array of Types. So the limitation to 7 entities does not exist anymore on these methods.

This is a Code Test from the Dapper Repo showing how to use one of these new methods:

public async Task TestMultiMapArbitraryWithSplitAsync()
    {
        const string sql = @"select 1 as id, 'abc' as name, 2 as id, 'def' as name";
        var productQuery = await connection.QueryAsync<Product>(sql, new[] { typeof(Product), typeof(Category) }, (objects) => {
            var prod = (Product)objects[0];
            prod.Category = (Category)objects[1];
            return prod;
        });

        var product = productQuery.First();
        // assertions
        product.Id.IsEqualTo(1);
        product.Name.IsEqualTo("abc");
        product.Category.Id.IsEqualTo(2);
        product.Category.Name.IsEqualTo("def");
    }



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why