参考 :

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. 转载http协议

    转载自:https://blog.csdn.net/weixin_38051694/article/details/77777010 1.说一下什么是Http协议 对器客户端和 服务器端之间数据传输的 ...

  2. gtest 安装与使用

    打开资源管理器: nautilus . gtest 获取 从:https://www.bogotobogo.com/cplusplus/google_unit_test_gtest.php 获取gte ...

  3. HTML基础之HTML标签-html header(meta,title) html body(p,br,h,form,div,span,input,lable)

    摘自:http://www.imdsx.cn/index.php/2017/07/27/html0/ 一.HTML标签 <!DOCTYPE html> <!--标准的html规则,类 ...

  4. Linux学习8-CentOS部署自己本地的django项目

    前言 自己本地写好的django项目,如何部署到linux服务器上,让其他的小伙伴也能访问呢?本篇以centos系统为例,把本地写好的django项目部署到linux服务器上 环境准备: 环境准备: ...

  5. C++11 std::ref使用场景

    C++本身有引用(&),为什么C++11又引入了std::ref(或者std::cref)? 主要是考虑函数式编程(如std::bind)在使用时,是对参数直接拷贝,而不是引用.如下例子: # ...

  6. 解决docker镜像pull超时问题

    第一步:通过dig @114.114.114.114 registry-1.docker.io找到可用IP dig @114.114.114.114 registry-1.docker.io 第二步: ...

  7. maven build resources

    1.在我用springboot+mytatis时,生成完mapper后,然后访问网站总是报错 错误信息: Servlet.service() for servlet [dispatcherServle ...

  8. 对String中固定符号隔开的每项做无序不重复监测

    Response<List<String[]>> response = new Response<>(); // 引擎方式校验 // 在此对知识内容标签进行打标 t ...

  9. 解决bootstrap 模态框 数据清除 验证清空

    $("#switchModel").on("hidden.bs.modal", function () { $('#ware-form')[0].reset() ...

  10. Qt 拷贝内容到粘贴板 || 获取粘贴板内容

    QString source = ui->textEdit_code->toPlainText(); QClipboard *clipboard = QApplication::clipb ...