Slapper.AutoMapper 的使用

 

Slapper.AutoMapper 是專門將一資料集合,對應成巢狀式類別。
Slapper.AutoMapper 使用底線(_)去區分出巢狀式子資料。
Slapper.AutoMapper 常和 Dapper 配合使用。

演示範例如下
1.開一 .net core ConsoleApp 專案
2.安裝 Slapper.AutoMapper

1
$ Slapper.AutoMapper

3.於 Program.cs 填入以下程式碼範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// 範例一
var dictionary = new Dictionary<string, object> {
{ "Id", 1 },
{ "FirstName", "Clark" },
{ "LastName", "Kent" }
};

var person = Slapper.AutoMapper.MapDynamic<Person>(dictionary);

Console.WriteLine($"Id:{person.Id} FirstName:{person.FirstName} LastName:{person.LastName}");



// 範例二
// Slapper.AutoMapper 使用底線(_)去區分出巢狀式子資料
var dic = new Dictionary<string, object>
{
{ "CustomerId", 1 },
{ "FirstName", "Bob" },
{ "LastName", "Smith" },
{ "Orders_OrderId", 1 },
{ "Orders_OrderTotal", 50.50m },
{ "Orders_OrderDetails_OrderDetailId", 1 },
{ "Orders_OrderDetails_OrderDetailTotal", 25.00m }
};

var dic2 = new Dictionary<string, object>
{
{ "CustomerId", 1 },
{ "FirstName", "Bob" },
{ "LastName", "Smith" },
{ "Orders_OrderId", 1 },
{ "Orders_OrderTotal", 50.50m },
{ "Orders_OrderDetails_OrderDetailId", 2 },
{ "Orders_OrderDetails_OrderDetailTotal", 25.50m }
};

var list = new List<IDictionary<string, object>> { dic, dic2 };

// 清 Slapper.AutoMapper 快取
Slapper.AutoMapper.Cache.ClearInstanceCache();

// 特別指定以什麼欄位值相同時,可視為同一筆資料
Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(Customer), new List<string> { "CustomerId", "FirstName", "LastName" });

var customers = (Slapper.AutoMapper.Map<Customer>(list) as IEnumerable<Customer>).ToList();
Console.WriteLine();



public class Person
{
public int Id;
public string FirstName;
public string LastName;
}

public class Customer
{
public int CustomerId;
public string FirstName;
public string LastName;
public IList<Order> Orders;
}

public class Order
{
public int OrderId;
public decimal OrderTotal;
public IList<OrderDetail> OrderDetails;
}

public class OrderDetail
{
public int OrderDetailId;
public decimal OrderDetailTotal;
}

參考資料:
Slapper.AutoMapper