本次示例,我们单独创建一个 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项目实践的更多相关文章

  1. Hangfire项目实践分享

    Hangfire项目实践分享 目录 Hangfire项目实践分享 目录 什么是Hangfire Hangfire基础 基于队列的任务处理(Fire-and-forget jobs) 延迟任务执行(De ...

  2. Windows on Device 项目实践 3 - 火焰报警器制作

    在前两篇<Windows on Device 项目实践 1 - PWM调光灯制作>和<Windows on Device 项目实践 2 - 感光灯制作>中,我们学习了如何利用I ...

  3. Windows on Device 项目实践 2 - 感光灯制作

    在上一篇<Windows on Device 项目实践 1 - PWM调光灯制作>中,我们学习了如何利用Intel Galileo开发板和Windows on Device来设计并完成一个 ...

  4. Windows on Device 项目实践 1 - PWM调光灯制作

    在前一篇文章<Wintel物联网平台-Windows IoT新手入门指南>中,我们讲解了Windows on Device硬件准备和软件开发环境的搭建,以及Hello Blinky项目的演 ...

  5. Hangfire项目实践

    Hangfire项目实践分享 Hangfire项目实践分享 目录 Hangfire项目实践分享 目录 什么是Hangfire Hangfire基础 基于队列的任务处理(Fire-and-forget ...

  6. MVC项目实践,在三层架构下实现SportsStore,从类图看三层架构

    在"MVC项目实践,在三层架构下实现SportsStore-02,DbSession层.BLL层"一文的评论中,博友浪花一朵朵建议用类图来理解本项目的三层架构.于是就有了本篇: I ...

  7. MVC项目实践,在三层架构下实现SportsStore-02,DbSession层、BLL层

    SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...

  8. MVC项目实践,在三层架构下实现SportsStore-01,EF Code First建模、DAL层等

    SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...

  9. MVC项目实践,在三层架构下实现SportsStore-03,Ninject控制器工厂等

    SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...

随机推荐

  1. Delphi中Unicode转中文

    function UnicodeToChinese(inputstr: string): string; var i: Integer; index: Integer; temp, top, last ...

  2. JQuery实用技巧

    1.关于页面元素的引用通过jquery的$()引用元素包括通过id.class.元素名以及元素的层级关系及dom或者xpath条件等方法,且返回的对象为jquery对象(集合对象),不能直接调用dom ...

  3. 质量能量等效的泛化--物理学定律方程与等效原理的对应关系 Generalization of Mass-Energy Equivalence--Corresponding Relations between Equations of Physical Laws and Equiva

    前文所述,质能方程E=Mc^2可知质能等效,即可设计实验,使得实验无法分辨是何者变化. 泛化:所有的物理学定律方程都可看作方程两边的概念是等效的. 举几个栗子: 例一:F=ma--伊萨克爵士的代表作. ...

  4. 探索基于.NET下实现一句话木马之ashx篇

    0x01 前言 在渗透测试的时候各种PHP版的一句话木马已经琳琅满目,而.NET平台下的一句话木马则百年不变,最常见的当属下面这句 笔者感觉有必要挖坑一下.NET平台里的一句话木马,经过一番摸索填坑终 ...

  5. VS动态修改App.config中遇到的坑(宿主进程问题)

    昨天遇到了很奇怪的一个bug,具体描述如下: 这个系统是c/s架构的针对多个工厂做的资材管理系统,由于有很多个工厂,每个工厂都有自己的服务器.所以需要动态的改变连接字符串去链接不同的服务器. 由于这个 ...

  6. ASP.NET MVC 使用Unity实现Ioc

    为什么有这篇文章 最近在学ASP.NET MVC项目中使用Ioc,选用了Unity作为依赖注入的容器组件,在网上找了相关的文章简单实现了依赖注入,但想用文件配置的方式进行容器注入的注册,发现相关的文章 ...

  7. Data - Hadoop伪分布式配置 - 使用Hadoop2.8.0和Ubuntu16.04

    系统版本 anliven@Ubuntu1604:~$ uname -a Linux Ubuntu1604 4.8.0-36-generic #36~16.04.1-Ubuntu SMP Sun Feb ...

  8. postgresql-int,bigint,numeric效率测试

    在postgresql9.5的时候做过一个测试就是sum()的效率最终的测试结果是sum(int)>sum(numeric)>sum(bigint)当时比较诧异为啥sum(bigint)效 ...

  9. 【sping揭秘】13、Spring AOP一世&二世

    Spring AOP一世 Spring AOP中的advice Before advice 这个就是在方法执行之前执行,也就是在对应的joinpoint之前 spring AOP二世 开启aspect ...

  10. POJ 2610

    #include<iostream> #include<iomanip> using namespace std; int main() { //freopen("a ...