Flattening-复杂到简单

  Flattening 翻译为压扁、拉平、扁平化的意思,可以理解为使原有复杂的结构变得简化,我们先看下领域模型和DTO代码:

 1     public class Order
 2     {
 3         private readonly IList<OrderLineItem> _orderLineItems = new List<OrderLineItem>();
 4         public Customer Customer { get; set; }
 5         public OrderLineItem[] GetOrderLineItems()
 6         {
 7             return _orderLineItems.ToArray();
 8         }
 9         public void AddOrderLineItem(Product product, int quantity)
10         {
11             _orderLineItems.Add(new OrderLineItem(product, quantity));
12         }
13         public decimal GetTotal()
14         {
15             return _orderLineItems.Sum(li => li.GetTotal());
16         }
17     }
18
19     public class Product
20     {
21         public decimal Price { get; set; }
22         public string Name { get; set; }
23     }
24
25     public class OrderLineItem
26     {
27         public OrderLineItem(Product product, int quantity)
28         {
29             Product = product;
30             Quantity = quantity;
31         }
32         public Product Product { get; private set; }
33         public int Quantity { get; private set; }
34         public decimal GetTotal()
35         {
36             return Quantity * Product.Price;
37         }
38     }
39
40     public class Customer
41     {
42         public string Name { get; set; }
43     }
44
45     public class OrderDto
46     {
47         public string CustomerName { get; set; }
48         public decimal Total { get; set; }
49     }

  可以看到领域模型 Order 是很复杂的,但是对于业务场景中的OrderDto却很简单,只有 CustomerName和Total两个属性,AutoMapper配置代码:

 1         public void Example()
 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             // 配置 AutoMapper
18             Mapper.CreateMap<Order, OrderDto>();
19             // 执行 mapping
20             OrderDto dto = Mapper.Map<Order, OrderDto>(order);
21             Console.WriteLine("CustomerName:" + dto.CustomerName);
22             Console.WriteLine("Total:" + dto.Total);
23         }

  转换效果:

  可以看到配置相当的简单,只要设置下Order和OrderDto之间的类型映射就可以了,我们看OrderDto中的CustomerName和Total属性在领域模型Order中并没有与之相对性,没什么可以转换呢,感觉好神奇的样子,其实仔细发现这些属性的命名都有一定的规则,AutoMapper在做解析的时候会按照PascalCase(帕斯卡命名法),就是一种变量命名法,除了PascalCase还有Hungarian(匈牙利命名法)和camelCase(骆驼命名法),PascalCase就是指混合使用大小写字母来构成变量和函数的名字,首字母要大写,camelCase首字母小写,我们C#命名中,一般使用的是camelCase和PascalCase,比较高级的是PascalCase。

  但是为什么AutoMapper会解析Total呢?因为在领域模型Order中有个GetTotal()方法,AutoMapper会解析“Get”之后的单词,所以会与Total相对应,如果你把OrderDto的属性“Total”改为“Totals”,就会发现得到的“Totals”为0。理解了AutoMapper的解析方式,我们就要注意在编写变量、属性或是方法名称的时候一定要规范,这也是一种好的习惯。

Projection-简单到复杂

  Projection 翻译为投影,Flattening是由复杂结构简化,Projection正好相反,投影可以理解为由原始结构千变万化,我们看下两种转换结构:

 1     public class CalendarEvent
 2     {
 3         public DateTime EventDate { get; set; }
 4         public string Title { get; set; }
 5     }
 6
 7     public class CalendarEventForm
 8     {
 9         public DateTime EventDate { get; set; }
10         public int EventHour { get; set; }
11         public int EventMinute { get; set; }
12         public string Title { get; set; }
13     }

  CalendarEvent是原始结构,CalendarEventForm是我们需要转换后的结构,可以看到CalendarEventForm要比CalendarEvent结构复杂些,看下AutoMapper配置转换代码:

 1         public void Example()
 2         {
 3             var calendarEvent = new CalendarEvent
 4             {
 5                 EventDate = new DateTime(2008, 12, 15, 20, 30, 0),
 6                 Title = "Company Holiday Party"
 7             };
 8
 9             // 配置 AutoMapper
10             Mapper.CreateMap<CalendarEvent, CalendarEventForm>()
11                 .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.EventDate.Date))//定义映射规则
12                 .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.EventDate.Hour))//定义映射规则
13                 .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.EventDate.Minute));//定义映射规则
14
15             // 执行 mapping
16             CalendarEventForm form = Mapper.Map<CalendarEvent, CalendarEventForm>(calendarEvent);
17
18             Console.WriteLine("EventDate:"+form.EventDate);
19             Console.WriteLine("EventHour:" + form.EventHour);
20             Console.WriteLine("EventMinute:" + form.EventMinute);
21             Console.WriteLine("Title:" + form.Title);
22         }

  和Flattening不同的是,我们除了定义类型映射,还要自定义映射规则,src.EventDate.Date指向dest.EventDate,src.EventDate.Minute指向dest.EventMinute,src.EventDate.Hour指向dest.EventHour,当然我们还可以在MapFrom方法中做一些复杂的映射关系操作,MapFrom接受一个lambda表达式作为参数,可以是任何的Func表达式。Projection适用于由简单到复杂的结构映射,一般体现在业务场景很复杂的情况下。

  【更正:Projection也不一定适用在由简单到复杂的场景,应该说使用Projection就是把AutoMapper的映射配置交给用户来操作】

Configuration Validation-配置验证

  我们在使用Flattening的前提是我们需要转换的结构命名是没有错误的,但是如果我们没有使用PascalCase命名法,或者说我们命名是错误的,该怎么办呢?比如下面代码:

1         public class Source
2         {
3             public int SomeValue { get; set; }
4         }
5
6         public class Destination
7         {
8             public int SomeValuefff { get; set; }
9         }

  可以看到Source和Destination中的字段并不相对应,我们测试下AutoMapper映射:

  AssertConfigurationIsValid方法是验证结构映射的,如果配置不正确,会报“AutoMapperConfigurationException”异常错误,如何解决这个问题?你可能会说,就不能改下SomeValuefff的名称吗?这种方法可以,但是如果业务场景中必须要使用怎么办呢,看了上面Projection的映射配置,你可能想到解决方法了,如下:

1             Mapper.CreateMap<Source, Destination>()
2                 .ForMember(dest => dest.SomeValuefff, opt => opt.MapFrom(src => src.SomeValue));

  名称不对,我们可以自定义映射规则,虽然这种方式可以,但是如果业务场景中SomeValuefff并不需要,那我们改怎么办?既然有问题,就有解决之道,AutoMapper提供了Ignore方法,忽略不需要映射的数据结构,我们这样配置就可以了:

1             Mapper.CreateMap<Source, Destination>()
2                 .ForMember(dest => dest.SomeValuefff, opt => opt.Ignore());

Lists and Array-集合和数组

  有时候我们除了类型映射之外,还需要对集合类型进行映射,先看个示例:

 1             public void Example()
 2             {
 3                 var sources = new[]
 4                     {
 5                         new Source {Value = 5},
 6                         new Source {Value = 6},
 7                         new Source {Value = 7}
 8                     };
 9                 //配置AutoMapper
10                 Mapper.Initialize(cfg =>
11                 {
12                     cfg.CreateMap<Source, Destination>();
13                 });
14                 //配置和执行映射
15                 IEnumerable<Destination> ienumerableDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources);
16                 ICollection<Destination> icollectionDest = Mapper.Map<Source[], ICollection<Destination>>(sources);
17                 IList<Destination> ilistDest = Mapper.Map<Source[], IList<Destination>>(sources);
18                 List<Destination> listDest = Mapper.Map<Source[], List<Destination>>(sources);
19
20                 Console.WriteLine("ienumerableDest.Count:" + ienumerableDest.Count());
21                 Console.WriteLine("icollectionDest.Count:" + icollectionDest.Count());
22                 Console.WriteLine("ilistDest.Count:" + ilistDest.Count());
23                 Console.WriteLine("listDest.Count:" + listDest.Count());
24             }

  转换结果:

  Source和Destination结构类型只有一个Value属性,可以看到对集合类型映射也很简单,只需要执行Mapper.Map泛型方法,指定需要转换的集合类型即可,AutoMapper所支持的集合类型包括:

  • IEnumerable
  • IEnumerable<T>
  • ICollection
  • ICollection<T>
  • IList
  • IList<T>
  • List<T>
  • Arrays

  我们在使用Mapper.Map执行类型映射的时候,如果来源类型支持上述集合类型,我们可以把来源类型省略掉,因为AutoMapper会自动判断传入对象sources的类型,如下:

1                 IEnumerable<Destination> ienumerableDest = Mapper.Map<IEnumerable<Destination>>(sources);
2                 ICollection<Destination> icollectionDest = Mapper.Map<ICollection<Destination>>(sources);
3                 IList<Destination> ilistDest = Mapper.Map<IList<Destination>>(sources);
4                 List<Destination> listDest = Mapper.Map<List<Destination>>(sources);

  还有一种情况是,在使用集合类型类型的时候,类型之间存在继承关系,例如下面我们需要转换的类型:

 1             public class ParentSource
 2             {
 3                 public int Value1 { get; set; }
 4             }
 5             public class ChildSource : ParentSource
 6             {
 7                 public int Value2 { get; set; }
 8             }
 9             public class ParentDestination
10             {
11                 public int Value1 { get; set; }
12             }
13             public class ChildDestination : ParentDestination
14             {
15                 public int Value2 { get; set; }
16             }

  ChildSource继承ParentSource,ChildDestination继承ParentDestination,看下AutoMapper配置转换代码:

 1             public void Example()
 2             {
 3                 var sources = new[]
 4                     {
 5                         new ParentSource(),
 6                         new ChildSource(),
 7                         new ParentSource()
 8                     };
 9                 //配置AutoMapper
10                 Mapper.Initialize(cfg =>
11                 {
12                     cfg.CreateMap<ParentSource, ParentDestination>()
13                         .Include<ChildSource, ChildDestination>();
14                     cfg.CreateMap<ChildSource, ChildDestination>();
15                 });
16                 //配置和执行映射
17                 var destinations = Mapper.Map<ParentSource[], ParentDestination[]>(sources);
18                 Console.WriteLine("destinations[0] Type:" + destinations[0].GetType().ToString());
19                 Console.WriteLine("destinations[1] Type:" + destinations[1].GetType().ToString());
20                 Console.WriteLine("destinations[2] Type:" + destinations[2].GetType().ToString());
21             }

  转换结果:

  注意在Initialize初始化CreateMap进行类型映射配置的时候有个Include泛型方法,签名为:“Include this configuration in derived types' maps”,大致意思为包含派生类型中配置,ChildSource是ParentSource的派生类,ChildDestination是ParentDestination的派生类,cfg.CreateMap<ParentSource, ParentDestination>().Include<ChildSource, ChildDestination>(); 这段代码只是说明ParentSource和ChildSource之间存在的关系,我们如果把这段代码注释掉,就会报上面“AutoMapperMappingException”类型指定不正确的异常错误,如果我们把下面这段代码:“cfg.CreateMap<ChildSource, ChildDestination>();”注释掉,转换结果为:

  虽然没有报“AutoMapperMappingException”异常,但是可以看出AutoMapper并没有从ChildSource类型映射到ChildDestination类型,而是自动映射到基类型,上面那段映射代码只是说明派生类和基类之间存在的关系,如果派生类需要映射的话,是需要添加派生类的映射的。

Nested mappings-嵌套映射

  我们上面说的集中映射方式都是简单类型映射,就是类型中并不包含其他类型的映射,如何在嵌套类型中执行映射?请看下面示例:

 1             public class OuterSource
 2             {
 3                 public int Value { get; set; }
 4                 public InnerSource Inner { get; set; }
 5             }
 6             public class InnerSource
 7             {
 8                 public int OtherValue { get; set; }
 9             }
10             public class OuterDest
11             {
12                 public int Value { get; set; }
13                 public InnerDest Inner { get; set; }
14             }
15             public class InnerDest
16             {
17                 public int OtherValue { get; set; }
18             }

  OuterSource和OuterDest类型是我们需要映射的类型,可以看到OuterSource类型中嵌套了InnerSource类型,OuterDest类型中嵌套了InnerDest类型,AutoMapper类型映射配置代码:

 1             public void Example()
 2             {
 3                 var source = new OuterSource
 4                 {
 5                     Value = 5,
 6                     Inner = new InnerSource { OtherValue = 15 }
 7                 };
 8                 //配置AutoMapper
 9                 Mapper.CreateMap<OuterSource, OuterDest>();
10                 Mapper.CreateMap<InnerSource, InnerDest>();
11                 //验证类型映射是否正确
12                 Mapper.AssertConfigurationIsValid();
13                 //执行映射
14                 var dest = Mapper.Map<OuterSource, OuterDest>(source);
15                 Console.WriteLine("dest.Value:" + dest.Value);
16                 Console.WriteLine("dest.Inner is null:" + (dest.Inner == null ? "true" : "false"));
17                 Console.WriteLine("dest.Inner.OtherValue:" + dest.Inner.OtherValue);
18             }

  转换结果:

  上面代码中可以看出,对于嵌套映射,我们不需要配置什么,只要指定下类型映射关系和嵌套类型映射关系就可以了,也就是这段代码:“Mapper.CreateMap<InnerSource, InnerDest>();” 其实我们在验证类型映射的时候加上Mapper.AssertConfigurationIsValid(); 这段代码看是不是抛出“AutoMapperMappingException”异常来判断类型映射是否正确,因为AssertConfigurationIsValid方法没有返回值,只能在catch中捕获了,个人感觉AutoMapper可以提供个bool类型的返回值,验证成功则返回true。

本文转自田园里的蟋蟀博客园博客,原文链接:http://www.cnblogs.com/xishuai/p/3700052.html,如需转载请自行联系原作者

DTO与Domin Model相互转换(上)相关推荐

  1. 【AutoMapper官方文档】DTO与Domin Model相互转换(上)

    [AutoMapper官方文档]DTO与Domin Model相互转换(上) 原文: [AutoMapper官方文档]DTO与Domin Model相互转换(上) 写在前面 AutoMapper目录: ...

  2. 【AutoMapper官方文档】DTO与Domin Model相互转换(中)

    写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...

  3. 【AutoMapper官方文档】DTO与Domin Model相互转换(下)

    Mapping Inheritance-映射继承 关于映射继承,其实在"Lists and Array-集合和数组"这一节点有提到,但是只是说明下AutoMapper解决映射继承所 ...

  4. 自定义组件封装之-如何使用SwfityJSON实现JSON/Model相互转换

    最近在学习Swift的各种框架,在我的另一篇Swift框架学习之-数据解析SwiftyJSON,已经介绍过了如何使用SwfityJSON这个牛逼的纯Swift写的框架,这里就不作过多介绍,主要来说说我 ...

  5. django的model使用上容易遇到的坑,default=datetime.now和auto_now、null和blank、save和update、bulk_create

    一.django设置字段动态默认时间的四种方式: from django.db import models from datetime import datetimeclass User(models ...

  6. idea 下划线字段转驼峰_Java如何实现数据库中表字段的下划线和驼峰式命名的Model相互转换,很方便的...-Go语言中文社区...

    其实通过逆向工程,然后去配置一些config,就可以实现,从Table到Model的相互转换,而且,对于下划线命名的Table字段,实现驼峰式命名的Model ,有时候我们只是做个测试,或者自己基于数 ...

  7. linux thread model . Linux上posix线程库实现原理讨论

    http://blog.csdn.net/fanbird2008/article/details/6752853 Linux上posix线程库实现原理讨论 说明一下,这个问题困扰我好长时间,因为正如使 ...

  8. java automapper 使用_AutoMapper使用

    前言:前篇搭建了下WCF的代码,就提到了DTO的概念,对于为什么要有这么一个DTO的对象,上章可能对于这点不太详尽,在此不厌其烦再来提提它的作用: 从安全上面考虑,领域Model都带有领域业务,让Cl ...

  9. C#进阶系列——DDD领域驱动设计初探(五):AutoMapper使用

    前言:前篇搭建了下WCF的代码,就提到了DTO的概念,对于为什么要有这么一个DTO的对象,上章可能对于这点不太详尽,在此不厌其烦再来提提它的作用: 从安全上面考虑,领域Model都带有领域业务,让Cl ...

最新文章

  1. 五分钟体验分布式调度框架xxl-job
  2. 使用Python中的Turtle库绘制简单的图形
  3. 面向 Java 开发人员的 Ajax: 构建动态的 Java 应用程序
  4. 计算机组成原理 — CPU — 缓存访问
  5. 用软件lm_sensors监测Linux系统和CPU温度(转)
  6. 【IM】关于参数模型和核模型的理解
  7. Use Asynchronous Apex
  8. ASP.NET设置数据格式与String.Format和DataFormatString使用总结
  9. 如何将SAP Multi Target应用部署到SAP云平台的Cloud Foundry环境去
  10. GPS 实景识别网络搭建项目(源码免费领取)
  11. ERP实施--常见问题
  12. sever2008 ad用户和计算机不见,windows-server-2008 – 当我使用Powershell将用户添加到安全组时,它们不会显示在AD中...
  13. Windows XP14个小技巧
  14. 单片机课设中期报告_本科论文中期报告
  15. 【Blender】导出地图任意位置的3D模型
  16. 计算机音乐出山,《出山》音乐
  17. Facebook 是神经制封号 还是有规则的封号?
  18. Keras实现两个优化器:Lookahead和LazyOptimizer
  19. 计算机专业的工匠精神例子,市计算机:传承中华传统文化,弘扬工匠精神
  20. springboot 事件监听器

热门文章

  1. APP如何发布到Google play 商店
  2. 【大学生Python】用字典和列表实现手机通讯录
  3. 城市公交系统车站客流量预测的研究现状
  4. 什么是 Multicast|组播
  5. 啊。啊。啊。https免费证书又到期了怎么办。。。。
  6. protopyte.js ajax
  7. AI实战:交规识别系统实战(源码共享)
  8. miRDeep2 学习及安装篇
  9. novas的verdi和debussy是干什么用的(关于debussy的一些介绍)
  10. Java Activiti 工作流引擎 springmvc SSM 流程审批 后台框架源码