Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper unlimited multi-mapping

Tags:

c#

dapper

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 ?

like image 540
Dimitar Dimitrov Avatar asked Dec 04 '13 03:12

Dimitar Dimitrov


2 Answers

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");
    }
like image 97
Hejo Avatar answered Oct 02 '22 10:10

Hejo


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.
like image 32
mosesfetters Avatar answered Oct 02 '22 10:10

mosesfetters