Asp.net core 学习笔记 (AutoMapper)
参考 :
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)的更多相关文章
- Asp.Net Core学习笔记:入门篇
Asp.Net Core 学习 基于.Net Core 2.2版本的学习笔记. 常识 像Django那样自动检查代码更新,自动重载服务器(太方便了) dotnet watch run 托管设置 设置项 ...
- ASP.NET Core 学习笔记 第一篇 ASP.NET Core初探
前言 因为工作原因博客断断续续更新,其实在很早以前就有想法做一套关于ASP.NET CORE整体学习度路线,整体来说国内的环境的.NET生态环境还是相对比较严峻的,但是干一行爱一行,还是希望更多人加入 ...
- Asp.net Core学习笔记
之前记在github上的,现在搬运过来 变化还是很大的,感觉和Nodejs有点类似,比如中间件的使用 ,努力学习ing... 优点 不依赖IIS 开源和跨平台 中间件支持 性能优化 无所不在的依赖注入 ...
- ASP.NET Core 学习笔记 第三篇 依赖注入框架的使用
前言 首先感谢小可爱门的支持,写了这个系列的第二篇后,得到了好多人的鼓励,也更加坚定我把这个系列写完的决心,也能更好的督促自己的学习,分享自己的学习成果.还记得上篇文章中最后提及到,假如服务越来越多怎 ...
- ASP.NET Core 学习笔记 第四篇 ASP.NET Core 中的配置
前言 说道配置文件,基本大多数软件为了扩展性.灵活性都会涉及到配置文件,比如之前常见的app.config和web.config.然后再说.NET Core,很多都发生了变化.总体的来说技术在进步,新 ...
- ASP.NET Core 学习笔记 第五篇 ASP.NET Core 中的选项
前言 还记得上一篇文章中所说的配置吗?本篇文章算是上一篇的延续吧.在 .NET Core 中读取配置文件大多数会为配置选项绑定一个POCO(Plain Old CLR Object)对象,并通过依赖注 ...
- Asp.net core 学习笔记 ( Data protection )
参考 : http://www.cnblogs.com/xishuai/p/aspnet-5-identity-part-one.html http://cnblogs.com/xishuai/p/a ...
- Asp.net core 学习笔记 SignalR
refer : https://kimsereyblog.blogspot.com/2018/07/signalr-with-asp-net-core.html https://github.com/ ...
- Asp.net core (学习笔记 路由和语言 route & language)
https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.1 https://doc ...
随机推荐
- [No0000196]一文读懂Java 11的ZGC为何如此高效
导读:GC是大部分现代语言内置的特性,Java 11 新加入的ZGC号称可以达到10ms 以下的 GC 停顿,本文作者对这一新功能进行了深入解析.同时还对还对这一新功能带来的其他可能性做了展望.ZGC ...
- WebService,ESB笔记
一.WebService是什么? WebService,是RPC的一样实现方式. RPC(Remote Procedure Call Protocol)--远程过程调用协议,它是一种通过网络从远程计算 ...
- 安装mysql服务时提示“找不到msvcp140.dll”
没有安装VC++2015版运行库导致的(Microsoft Visual C++ 2015 Redistributable),下载地址https://www.microsoft.com/en-us/d ...
- 19.1-uC/OS-III内存管理应用
一个处理器,在不断地分配和释放内存的过程中,一整块连续的内存被分散为很多离散的小块内存, 这些叫做内存碎片, 内存碎片过多会导致内存的浪费. uC/OS 的内存管理机制就是为了尽量减少内存碎片.大致的 ...
- [JavaScript] Frequently used method or solutions for issues
Get the file name from the file path Solution: var fileName = fullPath.replace(/^.*[\\\/]/, ''); // ...
- from dns.resolver import Resolver ImportError: No module named dns.resolver
from dns.resolver import Resolver ImportError: No module named dns.resolver python2运行BBScan时提示: from ...
- POJ 3080 Blue Jeans(Java暴力)
Blue Jeans [题目链接]Blue Jeans [题目类型]Java暴力 &题意: 就是求k个长度为60的字符串的最长连续公共子串,2<=k<=10 规定: 1. 最长公共 ...
- windows----------windows查看端口是否被占用
假如我们需要确定谁占用了我们的80端口在windows命令行窗口下执行: netstat -aon|findstr "80" TCP 127.0.0.1:80 0.0.0.0:0 ...
- python_函数式编程
函数式编程是一种编程范式 (而面向过程编程和面向对象编程也都是编程范式).在面向过程编程中,我们见到过函数(function):在面向对象编程中,我们见过对象(object).函数和对象的根本目的是以 ...
- shell脚本遍历当前目录下以数字命名的目录,并打印
#!/bin/bash single='' #定义以个位数为目录的集合double='' #定位十位数为目录的集合#按照需要可以根据实际情况再定义以百位数为目录的集合 for dir in `ls - ...