8分钟学会使用AutoMapper
一.什么是AutoMapper与为什么用它。
它是一种对象与对象之间的映射器,让AutoMapper有意思的就是在于它提供了一些将类型A映射到类型B这种无聊的实例,只要B遵循AutoMapper已经建立的惯例,那么大多数情况下就可以进行相互映射了。
二.如何使用?
直接nuget install-package automapper 简单到不能再简单了。
三.入门
定义了连个简单的Model:
public class Destination
{
public string name { get; set; }
public string InfoUrl { get; set; }
} public class Source
{
public string name { get; set; }
public string InfoUrl { get; set; }
public string aa { get; set; }
}
static void Main(string[] args)
{
Destination des = new Destination()
{
InfoUrl = "www.cnblogs.com/zaranet",
name ="张子浩"
};
Mapper.Initialize(x => x.CreateMap<Destination, Source>());
Source source = AutoMapper.Mapper.Map<Source>(des);
Console.WriteLine(source.InfoUrl);
}
Initialize方法是Mapper的初始化,里面可以写上CreateMap表达式,具体是谁和谁进行匹配。在之后就可以直接进行一个获取值的过程了,非常的简单。
四.映射前后操作
偶尔有的时候你可能需要在映射的过程中,你需要执行一些逻辑,这是非常常见的事情,所以AutoMapper给我们提供了BeforeMap和AfterMap两个函数。
Mapper.Initialize(x => x.CreateMap<Destination, Source>().BeforeMap(
(src,dest)=>src.InfoUrl ="https://"+src.InfoUrl).AfterMap(
(src,dest)=>src.name="真棒"+src.name));
其中呢,src是Destination对象,dest是Source,你呢就可以用这两个对象去获取里面的值,说白了这就是循环去找里面的值了。
五.条件映射
Mapper.Initialize(x => x.CreateMap<Destination, Source>().ForMember(dest => dest.InfoUrl,opt => opt.Condition(dest => dest.InfoUrl == "www.cnblogs.com/zaranet1")).ForMember(...(.ForMember(...))));
在条件映射中,通过ForMember函数,参数是一个委托类型Fun<>,其里面呢也是可以进行嵌套的,但一般来说一个就够用了。
六.AutoMapper配置
初始化配置是非常受欢迎的,每个领域都应该配置一次。
//初始化配置文件
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Aliens, Person>();
});
但是像这种情况呢,如果是多个映射,那么我们只能用Profile来配置,组织你的映射配置,并将配置放置到构造函数中(这种情况是5.x以上的版本),一个是以下的版本,已经被淘汰了。
5.0及以上版本:
public class AliensPersonProfile : Profile
{
public AliensPersonProfile()
{
CreateMap<Destination, Source>();
}
}
5.0以下版本(在早期版本中,使用配置方法而不是构造函数。 从版本5开始,Configure()已经过时。 它将在6.0中被删除。)
public class OrganizationProfile : Profile
{
protected override void Configure()
{
CreateMap<Foo, FooDto>();
}
}
然后在程序启动的时候初始化即可。
Mapper.Initialize(x=>x.AddProfile<AliensPersonProfile>());
七.AutoMapper的最佳实践
上文中已经说到了AutoMapper的简单映射,但是在实际项目中,我们应该有很多类进行映射,这么多的映射应该怎么组织,这是一个活生生的问题,这成为主映射器。
在主映射器中,组织了多个小映射器,Configuration为我们的静态配置入口类;Profiles文件夹为我们所有Profile类的文件夹。如果是MVC,我们需要在Global中调用,那我的这个是控制台的。
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile<DestinationSourceProfile>();
cfg.AddProfile(new StudentSourceProfile());
});
}
其中添加子映射,可以用以上两种方式。
public void Configuration(IAppBuilder app)
{
AutoMapperConfiguration.Configure();
}
八.指定映射字段
在实际业务环境中,你不可能说两个类的字段是一 一 对应的,这个时候我们就要对应它们的映射关系。
public class CalendarEvent
{
public DateTime Date { get; set; }
public string Title { get; set; }
} public class CalendarEventForm
{
public DateTime EventDate { get; set; }
public int EventHour { get; set; }
public int EventMinute { get; set; }
public string DisplayTitle { get; set; }
}
在这两个类中,CalendarEvent的Date将被拆分为CalendarEventForm的日期、时、分三个字段,Title也将对应DisplayTitle字段,那么相应的Profile定义如下:
public class CalendarEventProfile : Profile
{
public CalendarEventProfile()
{
CreateMap<CalendarEvent, CalendarEventForm>()
.ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.Date.Date))
.ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.Date.Hour))
.ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.Date.Minute))
.ForMember(dest => dest.DisplayTitle, opt => opt.MapFrom(src => src.Title));
}
}
main方法通过依赖注入,开始映射过程,下图是代码和图。
static void Main(string[] args)
{
CalendarEvent calendar = new CalendarEvent()
{
Date = DateTime.Now,
Title = "Demo Event"
};
AutoMapperConfiguration.Configure();
CalendarEventForm calendarEventForm = Mapper.Map<CalendarEventForm>(calendar);
Console.WriteLine(calendarEventForm);
}

那么最后呢,如果是反向的映射,一定回缺少属性,那么就你就可以obj.属性进行赋值。
附AutoHelper封装类
/// <summary>
/// AutoMapper扩展帮助类
/// </summary>
public static class AutoMapperHelper
{
/// <summary>
/// 类型映射
/// </summary>
public static T MapTo<T>(this object obj)
{
if (obj == null) return default(T);
Mapper.CreateMap(obj.GetType(), typeof(T));
return Mapper.Map<T>(obj);
}
/// <summary>
/// 集合列表类型映射
/// </summary>
public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
{
foreach (var first in source)
{
var type = first.GetType();
Mapper.CreateMap(type, typeof(TDestination));
break;
}
return Mapper.Map<List<TDestination>>(source);
}
/// <summary>
/// 集合列表类型映射
/// </summary>
public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
{
//IEnumerable<T> 类型需要创建元素的映射
Mapper.CreateMap<TSource, TDestination>();
return Mapper.Map<List<TDestination>>(source);
}
/// <summary>
/// 类型映射
/// </summary>
public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
where TSource : class
where TDestination : class
{
if (source == null) return destination;
Mapper.CreateMap<TSource, TDestination>();
return Mapper.Map(source, destination);
}
/// <summary>
/// DataReader映射
/// </summary>
public static IEnumerable<T> DataReaderMapTo<T>(this IDataReader reader)
{
Mapper.Reset();
Mapper.CreateMap<IDataReader, IEnumerable<T>>();
return Mapper.Map<IDataReader, IEnumerable<T>>(reader);
}
}
}
8分钟学会使用AutoMapper的更多相关文章
- 5分钟学会使用Less预编译器
5分钟学会使用Less预编译器 Less是什么? LESS CSS是一种动态样式语言,属于CSS预处理语言的一种,它使用类似CSS的语法为CSS赋予了动态语言的特性,如变量.继承.运算.函数等,更方便 ...
- 【grunt第二弹】30分钟学会使用grunt打包前端代码(02)
前言 上一篇博客,我们简单的介绍了grunt的使用,一些基础点没能覆盖,我们今天有必要看看一些基础知识 [grunt第一弹]30分钟学会使用grunt打包前端代码 配置任务/grunt.initCon ...
- 《量化投资:以MATLAB为工具》连载(2)基础篇-N分钟学会MATLAB(中)
http://www.matlabsky.com/thread-43937-1-1.html <量化投资:以MATLAB为工具>连载(3)基础篇-N分钟学会MATLAB(下) ...
- 《量化投资:以MATLAB为工具》连载(1)基础篇-N分钟学会MATLAB(上)
http://blog.sina.com.cn/s/blog_4cf8aad30102uylf.html <量化投资:以MATLAB为工具>连载(1)基础篇-N分钟学会MATLAB(上) ...
- [分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例)
[分享] 史上最简单的封装教程,五分钟学会封装系统(以封装Windows 7为例) 踏雁寻花 发表于 2015-8-23 23:31:28 https://www.itsk.com/thread-35 ...
- 50分钟学会Laravel 50个小技巧
50分钟学会Laravel 50个小技巧 时间 2015-12-09 17:13:45 Yuansir-web菜鸟 原文 http://www.yuansir-web.com/2015/12/09 ...
- 10分钟学会Linux
10分钟学会Linux有点夸张,可是能够让一个新手初步熟悉Linux中最重要最主要的知识,本文翻译的英文网页在众多Linux入门学习的资料中还是很不错的. 英文地址:http://freeengine ...
- PHP学习过程_Symfony_(3)_整理_十分钟学会Symfony
这篇文章主要介绍了Symfony学习十分钟入门教程,详细介绍了Symfony的安装配置,项目初始化,建立Bundle,设计实体,添加约束,增删改查等基本操作技巧,需要的朋友可以参考下 (此文章已被多人 ...
- 30分钟学会使用Spring Web Services基础开发
时隔一年终于又推出了一篇30分钟系列,上一篇<30分钟学会反向Ajax>是2016年7月的事情了.时光荏苒,岁月穿梭.虽然一直还在从事Java方面的开发工作,但是私下其实更喜欢使用C++. ...
随机推荐
- 测试工作之--adb代码
1.抓log方法 (bat文件) mkdir D:\logcatset /p miaoshu=请描述操作:adb logcat -v threadtime > D:\logcat\%miaosh ...
- 指针*p,p,&p等辨别
#include<iostream> #include<iomanip> #include<cmath> using namespace std; int main ...
- lsblk
linux磁盘命令-lsblk显现磁盘阵列分组 lsblk(list block devices)能列出系统上所有的磁盘. lsblk [-dfimpt] [device] 选项与参数: -d :仅列 ...
- Navicat Premium 12.1.11.0安装与激活
本文介绍Navicat Premium 12.1.11.0的安装.激活与基本使用. 博主所提供的激活文件理论支持Navicat Premium 12.0.x系列和Navicat Premium 12. ...
- 图论之最短路径floyd算法
Floyd算法是图论中经典的多源最短路径算法,即求任意两点之间的最短路径. 它可采用动态规划思想,因为它满足最优子结构性质,即最短路径序列的子序列也是最短路径. 举例说明最优子结构性质,上图中1号到5 ...
- Python PE8 编程规范
1.使用四个空格而不是tab进行缩进 2.默认使用utf-8编码 3.尽量不要使用魔术方法 4.类中使用self作为默认参数 5.命名时,尽量使用驼峰式或单词+下划线,要保证见名知意 6.操作符和逗号 ...
- fildder
来自 墨痕 :https://home.cnblogs.com/u/ink-marks/ FIDDLER的使用方法及技巧总结 一.FIDDLER快速入门及使用场景 Fiddler的官方网站:htt ...
- Httpclient代码
/// <summary> /// 显示 /// </summary> /// <returns></returns> public ActionRes ...
- unittest生产html测试报告
需要添加HTMLTestRunner.py文件,我用的ubuntu16.04下的python3.5.2,所以我放在/usr/lib/python3.5下 import unittest import ...
- dx.jar文件问题,有没有同学知道怎么解决呀,这一步没法解决,后面就没办法跟着做了
Java Code 123456789101112 dx.jar文件问题,有没有同学知道怎么解决呀,这一步没法解决 - test] Unknown error: Unable to build: ...