本次示例,我们单独创建一个 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. [LintCode] Permutations

    http://www.lintcode.com/en/problem/permutations/# Given a list of numbers, return all possible permu ...

  2. TaskCreationOptions.LongRunning 运行比可用线程数更多的任务

    最近在学WebSocket,服务端需要监听多个WebSocket客户端发送的消息. 开始的解决方法是每个WebSocket客户端都添加一个线程进行监听,代码如下: /// <summary> ...

  3. ubuntu18.10安装redis遇到问题

    执行命令apt-get install redis-server 安装遇到的问题 1.出现apt-get被占用情况,用ps -a|grep apt ,杀死存在的apt进程 2.还不行就执行sudo f ...

  4. 背水一战 Windows 10 (50) - 控件(集合类): ItemsControl - 基础知识, 数据绑定, ItemsPresenter, GridViewItemPresenter, ListViewItemPresenter

    [源码下载] 背水一战 Windows 10 (50) - 控件(集合类): ItemsControl - 基础知识, 数据绑定, ItemsPresenter, GridViewItemPresen ...

  5. iOS-项目开发1-图片浏览器

    FFBrowserImageViewController 自定义的图片浏览器:支持图片双击放大,单击取消,拖动取消. 重点: 1:在iOS11之后再布局是要将UIScrollViewContentIn ...

  6. Yii2 Apache + Nginx 路由重写

    一.什么是路由重写 原本的HTTP访问地址: www.test.com/index.php?r=post/view&id=100 表示这个请求将由PostController 的 action ...

  7. python使用selector模块编写FTP

    server import os import socket import time import selectors BASE_DIR = os.path.dirname(os.path.abspa ...

  8. 【xsy2194】Philosopher set+线段树合并

    题目大意:给你一个长度为$n$的序列,有$m$次操作,每次操作是以下两种之一: 对某个区间内的数按照升序/降序排序,询问某个区间内数的积在十进制下首位数字是多少. 数据范围:$n,m≤2\times ...

  9. One-hot数据处理

    机器学习 数据预处理之独热编码(One-Hot Encoding)(转) 问题由来 在很多机器学习任务中,特征并不总是连续值,而有可能是分类值. 例如,考虑一下的三个特征: ["male&q ...

  10. (转)【学习笔记】通过netstat+rmsock查找AIX端口对应进程

    原文:http://www.oracleplus.net/arch/888.html https://www.ibm.com/support/knowledgecenter/zh/ssw_aix_72 ...