对象 - 对象映射的一个常见用法是获取一个复杂的对象模型,并将其展开成一个更简单的模型。 您可以采取复杂的模型,如:
1 public class Order
2 {
3 private readonly IList<OrderLineItem> _orderLineItems = new List<OrderLineItem>();
4
5 public Customer Customer { get; set; }
6
7 public OrderLineItem[] GetOrderLineItems()
8 {
9 return _orderLineItems.ToArray();
10 }
11
12 public void AddOrderLineItem(Product product, int quantity)
13 {
14 _orderLineItems.Add(new OrderLineItem(product, quantity));
15 }
16
17 public decimal GetTotal()
18 {
19 return _orderLineItems.Sum(li => li.GetTotal());
20 }
21 }
22
23 public class Product
24 {
25 public decimal Price { get; set; }
26 public string Name { get; set; }
27 }
28
29 public class OrderLineItem
30 {
31 public OrderLineItem(Product product, int quantity)
32 {
33 Product = product;
34 Quantity = quantity;
35 }
36
37 public Product Product { get; private set; }
38 public int Quantity { get; private set;}
39
40 public decimal GetTotal()
41 {
42 return Quantity*Product.Price;
43 }
44 }
45
46 public class Customer
47 {
48 public string Name { get; set; }
49 }
我们想把这个复杂的Order对象变成一个更简单的OrderDto,它只包含某个场景所需的数据:
1 public class OrderDto
2 {
3 public string CustomerName { get; set; }
4 public decimal Total { get; set; }
5 }
在AutoMapper中配置源/目标类型对时,配置程序会尝试将源类型上的属性和方法与目标类型上的属性相匹配。 如果对目标类型上的任何属性,方法或以“Get”为前缀的方法不存在源类型上,则AutoMapper会将目标成员名称拆分为单个单词(遵循帕斯卡拼写法约定)。
1 // Complex model
2
3 var customer = new Customer
4 {
5 Name = "George Costanza"
6 };
7 var order = new Order
8 {
9 Customer = customer
10 };
11 var bosco = new Product
12 {
13 Name = "Bosco",
14 Price = 4.99m
15 };
16 order.AddOrderLineItem(bosco, 15);
17
18 // Configure AutoMapper
19
20 Mapper.Initialize(cfg => cfg.CreateMap<Order, OrderDto>());
21
22 // Perform mapping
23
24 OrderDto dto = Mapper.Map<Order, OrderDto>(order);
25
26 dto.CustomerName.ShouldEqual("George Costanza");
27 dto.Total.ShouldEqual(74.85m);
我们使用CreateMap方法在AutoMapper中配置类型映射。 AutoMapper只能映射它所知道的类型对,因此我们必须使用CreateMap显式地注册了源/目标类型对。 要执行映射,我们使用Map方法。
在OrderDto类型上,Total属性与Order上的GetTotal()方法匹配。 CustomerName属性与Order上的Customer.Name属性相匹配。 只要我们适当地命名目标属性,我们不需要配置单个属性匹配。
2.投影
3.配置验证
4.列表和数组
5.嵌套映射
6.自定义类型转换器
7.自定义值解析器
8.空替换
9.映射操作之前和之后
10.依赖注入
11.映射继承
12.可查询扩展(LINQ)
13.配置
14.条件映射
15.开放泛型
16.了解您的映射
来源:https://www.cnblogs.com/hugogoos/p/6240245.html