Dapper - Result Multi-Mapping

Description

Extension methods can be used to execute a query and map the result to a strongly typed list with relations.

The relation can be either:

These extension methods can be called from any object of type IDbConnection.

Example - Query Multi-Mapping (One to One)

Query method can execute a query and map the result to a strongly typed list with a one to one relation.

  1. string sql = "SELECT * FROM Invoice AS A INNER JOIN InvoiceDetail AS B ON A.InvoiceID = B.InvoiceID;";
  2. using (var connection = My.ConnectionFactory())
  3. {
  4. connection.Open();
  5. var invoices = connection.Query<Invoice, InvoiceDetail, Invoice>(
  6. sql,
  7. (invoice, invoiceDetail) =>
  8. {
  9. invoice.InvoiceDetail = invoiceDetail;
  10. return invoice;
  11. },
  12. splitOn: "InvoiceID")
  13. .Distinct()
  14. .ToList();
  15. }

Example - Query Multi-Mapping (One to Many)

Query method can execute a query and map the result to a strongly typed list with a one to many relations.

  1. string sql = "SELECT TOP 10 * FROM Orders AS A INNER JOIN OrderDetails AS B ON A.OrderID = B.OrderID;";
  2. using (var connection = new SqlConnection(FiddleHelper.GetConnectionStringSqlServerW3Schools()))
  3. {
  4. var orderDictionary = new Dictionary<int, Order>();
  5. var list = connection.Query<Order, OrderDetail, Order>(
  6. sql,
  7. (order, orderDetail) =>
  8. {
  9. Order orderEntry;
  10. if (!orderDictionary.TryGetValue(order.OrderID, out orderEntry))
  11. {
  12. orderEntry = order;
  13. orderEntry.OrderDetails = new List<OrderDetail>();
  14. orderDictionary.Add(orderEntry.OrderID, orderEntry);
  15. }
  16. orderEntry.OrderDetails.Add(orderDetail);
  17. return orderEntry;
  18. },
  19. splitOn: "OrderDetailID")
  20. .Distinct()
  21. .ToList();
  22. Console.WriteLine("Orders Count:" + list.Count);
  23. FiddleHelper.WriteTable(list);
  24. FiddleHelper.WriteTable(list.First().OrderDetails);
  25. }

Try it: .NET Core | .NET Framework