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 ...
随机推荐
- Nginx负载均衡后端健康检查
参考文档:https://www.cnblogs.com/kevingrace/p/6685698.html 本次使用第三方模块nginx_upstream_check_module的,要使用这个第三 ...
- 洛谷试炼场 - 关卡1-5 - 简单字符串 - (Done)
P1055 ISBN号码 #include<bits/stdc++.h> using namespace std; string s; ]={','X'}; int main() { ci ...
- zabbix3.2使用自带模板监控MySql
一.zabbix自带MySql模板监控项 Zabbix3.0之后已经有MySql监控模板了,所以我们只要引用ZabbixServer自带的模板即可.zabbix默认有14个监控项 我们只需获取监控项需 ...
- Oracle启动关闭
启动: [oracle@oracleSigle ~]$ sqlplus / as sysdba SQL*Plus: Release 11.2.0.1.0 Production on Wed Nov ...
- Linux命令:在线练习地址
1.https://www.tutorialspoint.com/unix_terminal_online.php 2.https://www.tutorialspoint.com/index.htm ...
- 绿色版mssql
1.安装2008绿色版,缺少对应的企业管理器,安装官方版本的提示电脑没有重启(已经重启后) 2.选择一个可用版本的mssql,2000的可以用,MSSQL2000-HaoSQL,自带企业管理器和查询器
- numpy 性能提升
a = np.array([1,2,3,4,5,1,2,2,2])c = np.unique(a)print(c) 对于很大的稀疏矩阵,我们不能用a[a>0]去取大于0的元素,而应该使用np.w ...
- Linux下安装Gensim
依赖软件包:numpy 直接使用pip安装: [root@mycentos ~]#pip install gensim 安装gensim的时候会遇到下面的一系列错误: Cannot uninstall ...
- PHP XAMPP windows环境安装扩展redis 致命错误: Class 'Redis' not found解决方法
PHP XAMPP windows环境安装扩展redis 致命错误: Class 'Redis' not found解决方法 1.电脑需要先安装redis服务端环境,并在安装目录下打开客户端redis ...
- 问题 1462: [蓝桥杯][基础练习VIP]Huffuman树
题目描述 Huffman树在编码中有着广泛的应用.在这里,我们只关心Huffman树的构造过程. 给出一列数{pi}={p0, p1, …, pn-1},用这列数构造Huffman树的过程如下: ...