说说AutoMapper那些事

项目中用到了DTO与Model之间的转换,因为model项目比较多,所以需要使用工具或者代码来实现快速的转换。AutoMapper就是一个很好的基于约定的object-object mapper.映射器。

Map规则:

AutoMapper默认是根据实体的属性名称来一一对应映射,你也可以手动的设置Map规则。

接下来举个栗子:

一、默认属性Map (DTO => Model)

准备实体

 1 namespace MapDemo
 2 {
 3     using System;
 4     using System.Collections.Generic;
 5     
 6     public partial class Service
 7     {
 8         public Service()
 9         {
10             this.ServiceDtl = new HashSet<ServiceDtl>();
11         }
12     
13         public int Id { get; set; }
14         public string Name { get; set; }
15         public Nullable<decimal> Price { get; set; }
16     
17         public virtual ICollection<ServiceDtl> ServiceDtl { get; set; }
18 
19     }
20 }
View Code
 1 namespace MapDemo
 2 {
 3     using System;
 4     using System.Collections.Generic;
 5     
 6     public partial class ServiceDtl
 7     {
 8         public int DtlId { get; set; }
 9         public string DtlName { get; set; }
10         public Nullable<int> Id { get; set; }
11     
12         public virtual Service Service { get; set; }
13     }
14 }
View Code

 准备Model

 1 namespace MapDemo.Model
 2 {
 3     class ServiceModel
 4     {
 5         public int Id { get; set; }
 6         public string Name { get; set; }
 7         public Nullable<decimal> Price { get; set; }
 8 
 9         public virtual ICollection<ServiceDtl> ServiceDtl { get; set; }
10 
11     }
12 }
View Code
 1 namespace MapDemo.Model
 2 {
 3     class ServiceDtlModel
 4     {
 5         public int DtlId { get; set; }
 6         public string DtlName { get; set; }
 7         public Nullable<int> Id { get; set; }
 8 
 9         public virtual Service Service { get; set; }
10     }
11 }
View Code

Mapper初始化:

Mapper.Initialize(cfg =>
{
  cfg.CreateMap<Service, ServiceModel>();
});

二、单表Map

var  serviceModel= Mapper.Map<ServiceModel>(service);

三、多表多层指定Map

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Service, ServiceModel>().ForMember(d => d.ServiceDtl, opt => opt.MapFrom(s => s.ServiceDtl));
    cfg.CreateMap<ServiceDtl, ServiceDtlModel>();
});

var  serviceModel= Mapper.Map<ServiceModel>(service);

这样service中就包含了ServiceDtl的项目,操作DB的时候进行反向Map,只需要操作主表,适用于多层表结构的操作,方便快捷,代码量少。

四、Model与Model之间Map

创建一个类似ServiceModel的模型CYService

 1 namespace MapDemo.Model
 2 {
 3     class CYService
 4     {
 5 
 6         public int Id { get; set; }
 7         public string Name { get; set; }
 8         public Nullable<decimal> Price { get; set; }
 9 
10     }
11 }
View Code
Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Service, CYService>();
});
var cyService = Mapper.Map<CYService>(newItem);

 

简单总结一下:

AutoMapper对于多表的层级操作十分方便,并且易于扩展。

但是项目中不建议直接使用Mapper.Map(),建议使用局部的mapEngine.Map()避免全局Map的影响。

具体参照官方解释:http://automapper.readthedocs.io/en/latest/index.html

原文地址:https://www.cnblogs.com/teyigou/p/AutoMapper.html