AutoMapper项目实践
本次示例,我们单独创建一个 AutoMapperService 的项目,用于放置映射配置文件,映射注册方法,映射公共方法。
1.映射配置文件
用于配置源实体到目标实体的映射
public class AccountProfile : AutoMapper.Profile
{
public AccountProfile()
{
//配置源实体AccountEntity到目标实体AccountViewModel的映射
CreateMap<AccountEntity, AccountViewModel>();
}
}
在项目中根据实际需求,按照业务创建不同的配置文件,比如用户配置文件UserProfile,配置用户相关实体的映射;订单配置文件OrderProfile配置订单业务相关实体的映射。
2.映射注册方法
public class MappingConfig
{
//public static void Init()
//{
// AutoMapper.Mapper.Initialize(cfg => {
// cfg.AddProfile<Profiles.AccountProfile>();
// });
//}
private static readonly Type BaseType = typeof(AutoMapper.Profile);
public static void RegisterMaps()
{
//加载 AutoMapperService的程序集
var assembly = System.Reflection.Assembly.Load("AutoMapperService");
//筛选出继承AutoMapper.Profile的映射配置文件,所有映射配置文件都必须继承AutoMapper.Profile
var types = assembly.GetTypes().Where(t => t.BaseType.Equals(BaseType));
//初始化映射配置文件
AutoMapper.Mapper.Initialize(cfg => {
cfg.AddProfiles(types);
});
}
}
本示例采用加载程序集统一注册方法,项目后期需要添加新的映射配置文件,直接添加即可
3.映射公共方法
3.1方法介绍
该方法包含常用的实体映射,List映射,IEnumerable映射等
public static class AutoMapperHelper
{
/// <summary>
/// 集合对集合
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="self"></param>
/// <returns></returns>
public static IEnumerable<TResult> MapTo<TResult>(this System.Collections.IEnumerable self)
{
if (self == null) throw new ArgumentNullException();
return (IEnumerable<TResult>)Mapper.Map(self, self.GetType(), typeof(IEnumerable<TResult>));
}
/// <summary>
/// 集合对集合
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="self"></param>
/// <returns></returns>
public static List<TResult> MapTo<TSource, TResult>(this List<TSource> self)
{
if (self == null) throw new ArgumentNullException();
return Mapper.Map<List<TSource>, List<TResult>>(self);
}
/// <summary>
/// 对象对对象
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="self"></param>
/// <returns></returns>
public static TResult MapTo<TResult>(this object self)
{
if (self == null) throw new ArgumentNullException();
return (TResult)Mapper.Map(self, self.GetType(), typeof(TResult));
}
}
3.2项目中如何使用
//添加AutoMapperService引用
using AutoMapperService;
public class AccountLogic
{
private readonly AccountService _accountSer;
public AccountLogic(AccountService accountSer)
{
this._accountSer = accountSer;
}
public AccountViewModel GetAccountById(int id)
{
//目标实体
AccountViewModel res = null;
//源实体
AccountEntity sourceEntity = _accountSer.GetAccount(id);
//调用MapTo方法向目标实体映射
//AccountEntity到AccountViewModel的映射,已在AccountProfile文件中配置
if (entity != null)
{
res = sourceEntity.MapTo<AccountViewModel>();
}
return res;
}
}
4.Web项目如何调用AutoMapper注册方法
本次示例,是在.Net Framework4.6.1框架下MVC模式开发,在web层中Global.asax文件下,在Application_Start方法调用AutoMapper注册方法即可
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(System.Web.Http.GlobalConfiguration.Configuration);
Filters.FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//调用AutoMapper注册方法
MappingConfig.RegisterMaps();
}
}
4.单元测试项目如何调用AutoMapper注册方法
在单元测试项目添加TestStart文件,如下内容,单元测试每次启动之前会自动调用Start方法,对AutoMapper的配置文件进行注册。若没有注册,在单元测试中调用3.2中的GetAccountById方法时,对象映射会失败。
/// <summary>
/// 单元测试启动之前初始化
/// </summary>
[TestClass]
public class TestStart
{
/// <summary>
/// 初始化逻辑方法
/// </summary>
[AssemblyInitialize]
public static void Start(TestContext context = null)
{
//调用AutoMapper的注册
AutoMapperService.MappingConfig.RegisterMaps();
}
}
AutoMapper项目实践的更多相关文章
- Hangfire项目实践分享
Hangfire项目实践分享 目录 Hangfire项目实践分享 目录 什么是Hangfire Hangfire基础 基于队列的任务处理(Fire-and-forget jobs) 延迟任务执行(De ...
- Windows on Device 项目实践 3 - 火焰报警器制作
在前两篇<Windows on Device 项目实践 1 - PWM调光灯制作>和<Windows on Device 项目实践 2 - 感光灯制作>中,我们学习了如何利用I ...
- Windows on Device 项目实践 2 - 感光灯制作
在上一篇<Windows on Device 项目实践 1 - PWM调光灯制作>中,我们学习了如何利用Intel Galileo开发板和Windows on Device来设计并完成一个 ...
- Windows on Device 项目实践 1 - PWM调光灯制作
在前一篇文章<Wintel物联网平台-Windows IoT新手入门指南>中,我们讲解了Windows on Device硬件准备和软件开发环境的搭建,以及Hello Blinky项目的演 ...
- Hangfire项目实践
Hangfire项目实践分享 Hangfire项目实践分享 目录 Hangfire项目实践分享 目录 什么是Hangfire Hangfire基础 基于队列的任务处理(Fire-and-forget ...
- MVC项目实践,在三层架构下实现SportsStore,从类图看三层架构
在"MVC项目实践,在三层架构下实现SportsStore-02,DbSession层.BLL层"一文的评论中,博友浪花一朵朵建议用类图来理解本项目的三层架构.于是就有了本篇: I ...
- MVC项目实践,在三层架构下实现SportsStore-02,DbSession层、BLL层
SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...
- MVC项目实践,在三层架构下实现SportsStore-01,EF Code First建模、DAL层等
SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...
- MVC项目实践,在三层架构下实现SportsStore-03,Ninject控制器工厂等
SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...
随机推荐
- 报错:Missing type map configuration or unsupported mapping
报错:Missing type map configuration or unsupported mapping □ 背景 当把View Model转换成Domain Model保存的时候,发生在Au ...
- 拟物设计和Angular的实现 - Material Design
Material Design是Google最新发布的跨平台统一视觉设计语言.直接翻译是物质设计,但是我更倾向于使用"拟物设计"更为准确. 据谷歌介绍,Material Desig ...
- cnblogs第一篇文章
大家好,以后我就在这里很多交流分享了!谢谢!
- atom编辑器社区插件推荐
atom是github出品的文本编辑器,为开发者又提供了一款易用.牛逼的文本编译器.在开始接触前端并从工作开始一直用webstrom来进行前端开发,开始使用时,被他各种强大神奇的功能给折服:支持zen ...
- 【BZOJ4755】 [Jsoi2016]扭动的回文串
BZOJ4755 [Jsoi2016]扭动的回文串 Solution 考虑对于他给出的 A中的一个回文串: B中的一个回文串: 或者某一个回文的扭动字符串S(i,j,k) 这样子几个限制,我们1,2就 ...
- springboot常用注解
@SpringBootApplication:包含了@ComponentScan.@Configuration和@EnableAutoConfiguration注解.其中@ComponentScan让 ...
- JSX 和 template 随想
就目前而言,我用到的前端页面开发框架主要有两种:以JSX为主的react和以template为主的vue. 虽然这两种方式各有千秋,但我其实更偏爱template多一些.为什么? 相较于灵活的JSX, ...
- 简单理解jQuery中$.getJSON、$.get、$.post、$.ajax用法
在WEB开发中异步请求方式普遍使用,ajax技术减少程序员的工作量,也提升用户交互体验.AJAX的四种异步请求方式都能实现基本需求,闲话不多说,直接切入正题. 1.$.getJSON $.getJSO ...
- Python(27)--文件相关处理的应用(增、删、改、查)
文件名为message,文件内容如下: global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info default ...
- hdu5745--La Vie en rose (DP+bitset)
好题,学到新姿势! 题意:给两个字符串 a 和 b ,b可以进行变换,规则是可以任意交换相邻两个字符的位置,但是不可以有交叉(例如3和4交换,5和6交换 互不影响,但是2和3,3和4就不可以).求a中 ...