Returning a single parameter as part of multi mapping query

c# dapper

Question

I have a scenario where I need to return a single column as part of a multi map query in Dapper.

I've simplified the example below but in essence the single column value (the int) I want to retrieve is not a property on the Post class (but is in the database table).

I want to fetch this value on it's own as use it in a manner similar to the following line from the example, where status is the int value in question:

post.SetSomeStatus(status);

Here is the code example:

  var sql = 
    @"select *, p.Status from #Posts p 
    left join #Users u on u.Id = p.OwnerId
    Order by p.Id";

    var data = connection.Query<Post, User, int, Post>(sql, (post, user, status) => { 
        post.Owner = user;
        post.SetSomeStatus(status);
        return post;
    });

    var post = data.First();

I'm seeing the following error with this code: Index was outside the bounds of the array.

Accepted Answer

The reason for the error: Index was outside of the bounds of the array was due to the way Dapper was splitting up the segments of the query response to be allocated across the return parameters Post, User & int in this example. The convention of Dapper is to split on the field ID or provide your own rules to split up the result set using the splitOn parameter.

To make the above example work:

  var sql = 
    @"select *, p.Status AS ID from #Posts p 
    left join #Users u on u.Id = p.OwnerId
    Order by p.Id";

    var data = connection.Query<Post, User, int, Post>(sql, (post, user, status) => { 
        post.Owner = user;
        post.SetSomeStatus(status);
        return post;
    });

    var post = data.First();

I found another question that also helped me: Correct use of Multimapping in Dapper




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