一、AutoMapper
说明:Automapper是一个object-object mapping(对象映射)工具,一般主要用于两个对象之间数据映射和交换。
二、安装程序集包
1、程序包管理控制台方式
Install-Package AutoMapper
2、Nuget方式
三、实体映射
1、两个实体之间的映射
using AutoMapper;
using System;
namespace ConsoleApp1
{
class Program
{
public class Source
{
public int Id { get; set; }
public string Content { get; set; }
}
public class DTOSource
{
public int Id { get; set; }
public string Content { get; set; }
}
static void Main(string[] args)
{
Mapper.Initialize(x => {
x.CreateMap<Source, DTOSource>();
});
Source s = new Source { Id = 1, Content = "123" };
DTOSource dto = Mapper.Map<DTOSource>(s);
Console.WriteLine("");
}
}
}

--这是一种最简单的使用,AutoMapper会更加字段名称去自动对于,忽略大小写。
2、两个实体不同字段之间的映射
将DTOSource中的Content的字段名改成Desc,此时只需要建立映射关系时,指定字段就可以了:
using AutoMapper;
using System;
namespace ConsoleApp1
{
class Program
{
public class Source
{
public int Id { get; set; }
public string Content { get; set; }
}
public class DTOSource
{
public int Id { get; set; }
public string Desc { get; set; }
}
static void Main(string[] args)
{
Mapper.Initialize(x => {
x.CreateMap<Source, DTOSource>().
ForMember(c => c.Desc, q => { q.MapFrom(z => z.Content);});
});
Source s = new Source { Id = 1, Content = "123" };
DTOSource dto = Mapper.Map<DTOSource>(s);
Console.WriteLine("");
}
}
}

四、ABP映射
1、手动映射或自动映射
属性什么都一一对应的,automap会自动映射:[
2、自定义映射-为了字段不一致的情况下使用自定义映射
表
[Table("Person")]
public class Person : FullAuditedEntity
{
public string Name { get; set; }
public int Sex { get; set; }
}
public class TestPersonDto
{
public string Name { get; set; }
public int Sex { get; set; }
}
2.1创建一个PersonMapper映射接口,然后一个一个声明实体之间的映射
internal static class PersonMapper
{
public static void CreateMappings(IMapperConfigurationExpression configuration)
{ //创建
configuration.CreateMap<TestPersonDto, Person>();
configuration.CreateMap<Person,TestPersonDto>();
}
}
2.2最后,不要忘记把这个自定义映射在项目名ApplicationModule中的Initialize()方法声明一下
public override void Initialize()
{
var thisAssembly = typeof(AbpDemoApplicationModule).GetAssembly();
IocManager.RegisterAssemblyByConvention(thisAssembly);
Configuration.Modules.AbpAutoMapper().Configurators.Add(
// Scan the assembly for classes which inherit from AutoMapper.Profile
cfg => {
cfg.AddProfiles(thisAssembly);
PersonMapper.CreateMappings(cfg);
}
);
}
如果字段更改即PersonEditDto的 MyName对应的Person的Name
修改一下我们映射接口
internal static class PersonMapper
{
public static void CreateMappings(IMapperConfigurationExpression configuration)
{ //创建
configuration.CreateMap<TestPersonDto, Person>().ForMember(a=>a.Name,b=>b.MapFrom(a=>a.MyName));
configuration.CreateMap<Person, TestPersonDtoo>().ForMember(a=>a.MyName,b=>b.MapFrom(a=>a.Name));
}
}