Dapper - Result Multi-Type

Description

ExecuteReader method is an extension method which can be called from any object of type IDbConnection. It can execute a query and map the result to a list of different types.

  1. string sql = "SELECT * FROM Invoice;";
  2. using (var connection = My.ConnectionFactory())
  3. {
  4. connection.Open();
  5. var invoices = new List<Invoice>();
  6. using (var reader = connection.ExecuteReader(sql))
  7. {
  8. var storeInvoiceParser = reader.GetRowParser<StoreInvoice>();
  9. var webInvoiceParser = reader.GetRowParser<WebInvoice>();
  10. while (reader.Read())
  11. {
  12. Invoice invoice;
  13. switch ((InvoiceKind) reader.GetInt32(reader.GetOrdinal("Kind")))
  14. {
  15. case InvoiceKind.StoreInvoice:
  16. invoice = storeInvoiceParser(reader);
  17. break;
  18. case InvoiceKind.WebInvoice:
  19. invoice = webInvoiceParser(reader);
  20. break;
  21. default:
  22. throw new Exception(ExceptionMessage.GeneralException);
  23. }
  24. invoices.Add(invoice);
  25. }
  26. }
  27. }