参考 :

http://www.cnblogs.com/xishuai/p/3700052.html

http://www.cnblogs.com/xishuai/p/3704435.html

http://www.cnblogs.com/xishuai/p/3708483.html

automapper 并不是 dotnet core 的东西啦,只是记入在这里而已.

automapper 是一个简单的库,帮我们处理对象和对象的映射.

我们做开发通常会用到 ef core,

entity 基本上对应 sql 的一个 table, 但是通常数据库的结构会比较复杂, 要范式,不要冗余嘛.

但是呢,我们在做 view , 或者在 post, put resource 的时候往往不需要那么多和那么复杂的结构.

所以就有了 DTO , data transfer object 的概念.

而 entity <-> DTO 就是一个很繁琐的映射. 于是就有了 automapper 这个比较智能的工具库.

nuget 安装 : AutoMapper.Extensions.Microsoft.DependencyInjection

在 service config 添加 services.AddAutoMapper();

定义一个 Profile (我的做法是把所有的映射都写在一起,一堆就是了,感觉比较容易找,遇到要添加 column 的情况下, 就有很多 dto 要跟着添加嘛)

    public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<Member, MemberDto>();
}
}

1. 复杂类型到简单类型

public class Member {
public Address address { get; set; }
} public class Address {
public string country { get; set; }
} public class MemberDto {
public string addressCountry { get; set; }
}

两层变一层

public class HomeController : Controller
{
private readonly IMapper Mapper;
public HomeController(
IMapper mapper
) {
Mapper = mapper;
}
public IActionResult Index()
{
var member = new Member { address = new Address { country = "Malaysia" } };
var memberDto = Mapper.Map<MemberDto>(member);
var result = memberDto.addressCountry; // Malaysia
return View();
}
}

这样就可以了.

2. 简单类型到复杂类型

用反转就可以了

CreateMap<Member, MemberDto>().ReverseMap();
// ReverseMap 是好东西, 但有些东西不能直接反转, 比如 ignore
CreateMap<Member, MemberDto>().ForMember(dest => dest.name, opt => opt.Ignore()).ReverseMap().ForPath(dest => dest.name, opt => opt.Ignore());
如果不写 ForPath 只有 to dto 的时候回 ignore.

3. 自定义映射

CreateMap<Member, MemberDto>().ForMember(dest => dest.addressCountry, opt => opt.MapFrom(sour => sour.address.country));

使用 ForMember + MapFrom 可以完全自己定义.

dest = destination 目的地, sour = source, automapper 就是 source -> destination 的概念.

4. ignore 无视

CreateMap<Member, MemberDto>().ForMember(dest => dest.name, opt => opt.Ignore()).ReverseMap().ForPath(dest => dest.name, opt => opt.Ignore());

5.collection

不需要任何新配置

var members = Mapper.Map<List<Member>>(membersDto);

6.继承

继承是当我们有这样的需求的时候

假设 Person -> Man -> Boy

var x = new Boy { propBoy = "da", propMan = "d", name = "a" };
var g = Mapper.Map<PersonDto>(x);

我们希望 g 是一个 BoyDto

CreateMap<Person, PersonDto>().Include<Man, ManDto>().Include<Boy, BoyDto>();
CreateMap<Man, ManDto>();
CreateMap<Boy, BoyDto>();

需要如上的配置才行哦, 缺一不可.

到这里我们可以看出来, automapper 的 config 主要就是针对, 当某个类型需要被映射到另一个类型时,它需要怎样的配置.

7. 原始类型转换

既然是类型转换,那 string 可以 to int 映射吗 ?

Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
Mapper.CreateMap<string, int>().ConvertUsing(stringValue => Convert.ToInt32(stringValue)); //表达式也可以

完全没有问题.

refer : http://docs.automapper.org/en/latest/Custom-type-converters.html?highlight=custom

8. 值得映射

上面说到有时候我们需要些自定义的映射,那是因为它原始没有嘛。但是如果一直写重复也不行。

所以还是可以封装的.

public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<Source, Destination>()
.ForMember(dest => dest.Total, opt => opt.MapFrom<CustomResolver>()));
}
} public class Source
{
public int Value1 { get; set; }
public int Value2 { get; set; }
} public class Destination
{
public int Total { get; set; }
} public class CustomResolver : IValueResolver<Source, Destination, int>
{
public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
{
return source.Value1 + source.Value2;
}
}

真实场景下, 把 Source 和 Destination 换成接口.

refer : http://docs.automapper.org/en/latest/Custom-value-resolvers.html

9. default value

  Mapper.CreateMap<Source, Destination>().ForMember(dest => dest.Value, opt => opt.NullSubstitute("Other Value"));

如果映射时 source 没有值,我们可以通过这里给一个 default 给 destination.

总结 :

automapper 就是帮助我们写映射的. 我们使用的时候一定要记得这一点,不要让它去做超出范围的事情.

Asp.net core 学习笔记 (AutoMapper)的更多相关文章

  1. Asp.Net Core学习笔记:入门篇

    Asp.Net Core 学习 基于.Net Core 2.2版本的学习笔记. 常识 像Django那样自动检查代码更新,自动重载服务器(太方便了) dotnet watch run 托管设置 设置项 ...

  2. ASP.NET Core 学习笔记 第一篇 ASP.NET Core初探

    前言 因为工作原因博客断断续续更新,其实在很早以前就有想法做一套关于ASP.NET CORE整体学习度路线,整体来说国内的环境的.NET生态环境还是相对比较严峻的,但是干一行爱一行,还是希望更多人加入 ...

  3. Asp.net Core学习笔记

    之前记在github上的,现在搬运过来 变化还是很大的,感觉和Nodejs有点类似,比如中间件的使用 ,努力学习ing... 优点 不依赖IIS 开源和跨平台 中间件支持 性能优化 无所不在的依赖注入 ...

  4. ASP.NET Core 学习笔记 第三篇 依赖注入框架的使用

    前言 首先感谢小可爱门的支持,写了这个系列的第二篇后,得到了好多人的鼓励,也更加坚定我把这个系列写完的决心,也能更好的督促自己的学习,分享自己的学习成果.还记得上篇文章中最后提及到,假如服务越来越多怎 ...

  5. ASP.NET Core 学习笔记 第四篇 ASP.NET Core 中的配置

    前言 说道配置文件,基本大多数软件为了扩展性.灵活性都会涉及到配置文件,比如之前常见的app.config和web.config.然后再说.NET Core,很多都发生了变化.总体的来说技术在进步,新 ...

  6. ASP.NET Core 学习笔记 第五篇 ASP.NET Core 中的选项

    前言 还记得上一篇文章中所说的配置吗?本篇文章算是上一篇的延续吧.在 .NET Core 中读取配置文件大多数会为配置选项绑定一个POCO(Plain Old CLR Object)对象,并通过依赖注 ...

  7. Asp.net core 学习笔记 ( Data protection )

    参考 : http://www.cnblogs.com/xishuai/p/aspnet-5-identity-part-one.html http://cnblogs.com/xishuai/p/a ...

  8. Asp.net core 学习笔记 SignalR

    refer : https://kimsereyblog.blogspot.com/2018/07/signalr-with-asp-net-core.html https://github.com/ ...

  9. Asp.net core (学习笔记 路由和语言 route & language)

    https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1 https://doc ...

随机推荐

  1. 通过阿里云命令行工具 aliyuncli 购买服务器

    开始想通过 aliyuncli 的 golang 源码进行编译安装(注:python 版的 aliyuncli 已不再维护),但没成功,详见 通过 golang 源码编译阿里云命令行工具 aliyun ...

  2. NOIP2018提高组初赛知识点

     (传说,在神秘的初赛中,选手们经常互相爆零以示友好……) 历年真题:ti.luogu.com.cn 以下标题中打*的是我认为的重点内容 一.关于计算机 (一)计算机组成 硬件组成: 1. 控制器(C ...

  3. FQ原理

    笔者在nginx反向代理篇讲了正向代理和反向代理的区别,今天着重讲其中的FQ是实现原理. 一.普遍的两种方式 1.vpn vpn它将客户端的IP数据报经过加密和二次封装后转发出去,客户端通过vpn上网 ...

  4. 八、UIViewController们之间的协作——Segue

    概述 正所谓“一生二,二生三,三生万物”,1个UIViewController没什么花样,多个UIViewController相互协作就有了各式各样丰富多彩的APP.但是UIViewControlle ...

  5. C++内存分区:堆、栈、自由存储区、全局/静态存储区和常量存储区

    日志                                                                                                  ...

  6. DX9 DirectX 索引缓存(IndexBuffer) 代码

    // @time: 2012.3.22 // @author: jadeshu // des: 索引缓存 //包含头文件 #include <Windows.h> #include < ...

  7. Gis数据处理

    几何投影和解析投影几何投影是将椭球面上的经纬线网投影到几何平面上,然后将几何面展为平面.几何投影可以分为方位投影.圆柱投影和圆锥投影.这三种投影纬线的形状不同.方位投影纬线的形状是同心圆:圆柱投影纬线 ...

  8. spring boot + vue + element-ui全栈开发入门——集成element-ui

     一.IDE开发工具 常用的开发工具有webstorm和sublime. 我个人喜好用Atom+插件的形式 打开Atom,在file --> settings --> packages中收 ...

  9. 玩转spring boot——结合docker

    前言 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 liunx机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有 ...

  10. Kubernetes持久化存储1——示例

    目录贴:Kubernetes学习系列 一.简介 存储管理与计算管理是两个不同的问题.Persistent Volume子系统,对存储的供应和使用做了抽象,以API形式提供给管理员和用户使用.要完成这一 ...