Last active
January 11, 2020 00:09
-
-
Save michaeloyer/ac20d3ef9e450c9559fac8fdbaecfe6f to your computer and use it in GitHub Desktop.
Dapper's Query 'map' and 'splitOn' parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Dapper; | |
using Microsoft.Data.Sqlite; | |
using Newtonsoft.Json; | |
namespace Dappering | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using var db = new SqliteConnection("Data Source=:memory:"); | |
db.Open(); | |
db.Execute(@" | |
CREATE TABLE Customers (CustomerID Integer Primary Key, Name Text); | |
INSERT INTO Customers VALUES (1, 'A'), (2, 'B'); | |
CREATE TABLE Orders (OrderID Integer Primary Key, OrderNumber Text, CustomerId Integer); | |
INSERT INTO Orders (OrderNumber, CustomerID) | |
VALUES ('O1', 1), | |
('O2', 2), | |
('O3', 2), | |
('O4', 2);"); | |
var orders = db.Query<Customer, Order, Order>( | |
sql: @"SELECT c.CustomerID, Name, OrderID, OrderNumber | |
FROM Customers c | |
JOIN Orders o ON o.CustomerID = c.CustomerID", | |
map: (customer, order) => | |
{ | |
order.CustomerName = customer.Name; | |
return order; | |
}, | |
splitOn: "CustomerID,OrderID"); | |
System.Console.WriteLine(JsonConvert.SerializeObject(orders, Formatting.Indented)); | |
/* | |
[ | |
{ | |
"OrderNumber": "O1", | |
"CustomerName": "A" | |
}, | |
{ | |
"OrderNumber": "O2", | |
"CustomerName": "B" | |
}, | |
{ | |
"OrderNumber": "O3", | |
"CustomerName": "B" | |
}, | |
{ | |
"OrderNumber": "O4", | |
"CustomerName": "B" | |
} | |
] | |
*/ | |
} | |
} | |
public class Customer | |
{ | |
public string Name { get; set; } | |
} | |
public class Order | |
{ | |
public string OrderNumber { get; set; } | |
public string CustomerName { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment