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优化.导航.分页.购物车.订单.产品管 ...
随机推荐
- Android-Kotlin-区间与for&List&Map简单使用
区间与for: package cn.kotlin.kotlin_base04 /** * 区间与for */ fun main(args: Array<String>) { /** * ...
- ASP.NET Core 2.1 源码学习之 Options[3]:IOptionsMonitor
前面我们讲到 IOptions 和 IOptionsSnapshot,他们两个最大的区别便是前者注册的是单例模式,后者注册的是 Scope 模式.而 IOptionsMonitor 则要求配置源必须是 ...
- python- 动态加载目录下所有的类
# 背景 自动化测试框架中model层下有很多类,用来操作mysql的,使用的时候需要把全部的类加载进来,需要使用到动态加载类 # 解决方法 使用pkgutil,内置的方法,常用的话有两个方法 ite ...
- WinForm中DataGridView的使用(一) - 基本使用
数据绑定 直接指定源数据(List<T>):this.DataSource = data; 通常也可以直接指定DataTable类型的数据 DataTable dt = new DataT ...
- 阿里云oss服务通用类
在webconfig中配置信息 <?xml version="1.0" encoding="utf-8"?><configuration> ...
- MQ的demo
public class WorkTest { @Test public void send() throws Exception{ //获取连接 Connection conn = ...
- file-loader引起的html-webpack-plugin坑
引言 最近,我们的一个后台系统要改版为基于react + redux + react-router + ant-design 技术栈,切换到当下比较新的技术来实现后台系统:在项目实施过程中,选择了基于 ...
- python中a,b=b,a原理
python中 a , b = b , a 可以将 a 和 b 的值交换 >>> a = 1 >>> b = 2 >>> a , b = ...
- POJ 2840
#include<iostream> #include<stdio.h> #include<string> using namespace std; int mai ...
- QQ gtk,bkn算法
public long GetGTK(string sKey) { ; , len = sKey.Length; i < len; ++i) { hash += (hash << ) ...