'Example of Dapper query with n number of Navigation Properties
I'm building a Dapper query with joins to 8 tables but apparently the Dapper SqlMapper
only supports 7.
I read in this article that there is an overload that takes n number of types:
public static IEnumerable<TReturn> Query<TReturn>(this IDbConnection cnn,
string sql,
Type[] types,
Func<object[], TReturn> map,
object param = null,
IDbTransaction transaction = null,
bool buffered = true,
string splitOn = "Id",
int? commandTimeout = null,
CommandType? commandType = null)
Could someone give me a simple example of how to use it?
This is what I used before for joins to less number of tables:
var sql = @"SELECT * FROM dbo.ComponentRelationship cr
JOIN dbo.ComponentRelationshipType crt ON crt.ComponentRelationshipTypeId = cr.ComponentRelationshipTypeId
JOIN dbo.Application fa ON fa.ApplicationId = cr.FromId
JOIN dbo.Application ta ON ta.ApplicationId = cr.ToId
ORDER BY fa.Name, ta.Name";
result = connection.Query<ComponentRelationship, ComponentRelationshipType, Application, Application, ComponentRelationship>(sql,
(cr, crt, fa, ft) =>
{
cr.ComponentRelationshipTypeName = crt.Name;
cr.FromName = fa.Name;
cr.ToName = ft.Name;
return cr;
}, splitOn: "ComponentRelationshipId,ComponentRelationshipTypeId,ApplicationId,ApplicationId");
Solution 1:[1]
I found the answer here.
const string sql = @"
select
rb.Id, rb.Name,
u1.*, u2.*, u3.*, u4.*, u5.*, u6.*, u7.*, u8.*, u9.*
from #ReviewBoards rb
inner join #Users u1 on u1.Id = rb.User1Id
inner join #Users u2 on u2.Id = rb.User2Id
inner join #Users u3 on u3.Id = rb.User3Id
inner join #Users u4 on u4.Id = rb.User4Id
inner join #Users u5 on u5.Id = rb.User5Id
inner join #Users u6 on u6.Id = rb.User6Id
inner join #Users u7 on u7.Id = rb.User7Id
inner join #Users u8 on u8.Id = rb.User8Id
inner join #Users u9 on u9.Id = rb.User9Id";
var types = new[] { typeof(ReviewBoard), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User), typeof(User) };
Func<object[], ReviewBoard> mapper = (objects) =>
{
var board = (ReviewBoard)objects[0];
board.User1 = (User)objects[1];
board.User2 = (User)objects[2];
board.User3 = (User)objects[3];
board.User4 = (User)objects[4];
board.User5 = (User)objects[5];
board.User6 = (User)objects[6];
board.User7 = (User)objects[7];
board.User8 = (User)objects[8];
board.User9 = (User)objects[9];
return board;
};
var data = connection.Query<ReviewBoard>(sql, types, mapper).ToList();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amit Joshi |