ABP中的AutoMapper
在我们的业务中经常需要使用到类型之间的映射,特别是在和前端页面进行交互的时候,我们需要定义各种类型的Dto,并且需要需要这些Dto和数据库中的实体进行映射,对于有些大对象而言,需要赋值太多的属性,这样往往会使整个代码不够简洁和明了,有了AutoMapper之后我们就可以通过很少的代码来完成这样一个映射的过程,在了解当前的代码之前,你最好先读一下ABP文档中对于这个部分的介绍,更详细的介绍你可以参考这里。
一 基础篇
1 注入IObjectMapper接口
通过接口注入IObjectMapper对象,如果使用ABP框架的话所有继承自ApplicationService的应用服务都可以获取定义于AbpServiceBase中已经注入的公用属性ObjectMapper对象。
2 定义映射关系
在当前继承自AbpModule的类下面的Initialize()方法中添加映射关系
public override void Initialize() {
IocManager.RegisterAssemblyByConvention(typeof(DcsApplicationModule).GetAssembly());
IocManager.AddSdtSession<Guid>();
Configuration.Modules.AbpAutoMapper().Configurators.Add(config => {
config.CreateMissingTypeMaps = true;
#region 客户售后档案,客户售后档案与车辆关系
config.CreateMap<CustomerSoldDto, CustomerSold>(MemberList.Source);
config.CreateMap<CustomerVehicleSoldDto, CustomerVehicleSold>(MemberList.Source);
config.CreateMap<CustomerSoldExtendedInput, CustomerSoldExtended>(MemberList.Source)
.ForMember(c => c.C4cmCode, o => o.MapFrom(m => m.CrmCode))
.ForMember(c => c.ReferrerPhone, o => o.MapFrom(m => m.Referrer));
config.CreateMap<CustomerSoldSyncInput, CustomerSold>(MemberList.Source)
.ForMember(c => c.CustomerSoldExtended, o => o.MapFrom(m => m.CustomerSoldExtended))
.ForMember(c => c.JobName, o => o.MapFrom(m => m.JobTitle));
#endregion 客户售后档案,客户售后档案与车辆关系
});
}
上面的代码中我们可以使用ForMember方法来定义自己的映射规则。
3 使用ObjectMapper映射实体关系
在有了第一步的工作后,我们就可以在业务代码中调用_objectMapper.Map<T>(input),或者是_objectMapper.Map(input,oldEntity)这种方式来实现从Dto到数据库实体的映射关系。
二 进阶篇
1 定义Profile来分散映射关系
如果我们把所有的映射关系都写在Module的Initialize()方法里面,我们发现对于一个大的项目简直就是一个灾难,因为这个映射关系实在是太多,整个类超级大,现在有一个解决方案就是定义自己的XXXProfile,但是需要继承自基类Profile类。
public class EngineMaintainApplyProfile : Profile {
public EngineMaintainApplyProfile() {
CreateMap<EngineMaintainApply, QueryEngineMaintainApplyOutput>(MemberList.Destination)
.ForMember(d => d.BreakMaintainMark, options => options.MapFrom(s => s.VehicleSold.BreakMaintainMark));
CreateMap<EngineMaintainApplyAth, EngineMaintainApplyAthDto>(MemberList.Destination);
CreateMap<EngineMaintainApply, QueryEngineMaintainApplyWithDetailsOutput>(MemberList.Destination)
.ForMember(d => d.Attachments, options => options.MapFrom(s => s.EngineMaintainApplyAths))
.ForMember(d => d.ProductCode, options => options.MapFrom(s => s.VehicleSold.ProductCode))
.ForMember(d => d.EngineCode, options => options.MapFrom(s => s.VehicleSold.EngineCode))
.ForMember(d => d.TransmissionSn, options => options.MapFrom(s => s.VehicleSold.TransmissionSn))
.ForMember(d => d.Color, options => options.MapFrom(s => s.VehicleSold.Color))
.ForMember(d => d.VehiclePurpose, options => options.MapFrom(s => s.VehicleSold.VehiclePurpose))
.ForMember(d => d.InvoiceDate, options => options.MapFrom(s => s.VehicleSold.InvoiceDate))
.ForMember(d => d.SalePrice, options => options.MapFrom(s => s.VehicleSold.SalePrice))
.ForMember(d => d.ProductionDate, options => options.MapFrom(s => s.VehicleSold.ProductionDate))
.ForMember(d => d.VehicleSaleDate, options => options.MapFrom(s => s.VehicleSold.SaleDate));
CreateMap<AddEngineMaintainApplyInput, EngineMaintainApply>(MemberList.Source)
.ForMember(d => d.VehicleSoldId, options => options.MapFrom(s => s.VehicleId))
.ForMember(d => d.ExtensionMaintainBeginDate, options => options.MapFrom(s => s.SaleDate))
.ForMember(d => d.EngineMaintainApplyAths, options => options.Ignore());
CreateMap<UpdateEngineMaintainApplyInput, EngineMaintainApply>(MemberList.Source)
.ForMember(d => d.RowVersion, options => options.Ignore())
.ForMember(d => d.EngineMaintainApplyAths, options => options.Ignore());
}
}
使用这个方法的时候需要注意需要在Initialize方法里面添加映射,例如下面的方式。
public override void Initialize() {
IocManager.RegisterAssemblyByConvention(typeof(DcsApplicationModule).GetAssembly());
Configuration.Modules.AbpAutoMapper().Configurators.Add(config => {
config.AddMaps(typeof(DcsApplicationModule).GetAssembly());
});
}
2 添加自动映射关系
这个需要特别注意,当我们的Dto和目标实体每个字段都能一一对应的情况下,在AutoMapper<8.1.1这个版本的时候能够自动识别并映射,但是当升级到这个版本的时候这个特性会去掉,关于这个内容请点击这里了解详情,AutoMapper的官方暂时给了一个过渡的方案,那就是设置CreateMissingTypeMaps属性设置为true,就像下面的例子。
public override void Initialize() {
IocManager.RegisterAssemblyByConvention(typeof(DcsApplicationModule).GetAssembly());
Configuration.Modules.AbpAutoMapper().Configurators.Add(config => {
config.CreateMissingTypeMaps = true;
});
}
但是这只是一个过渡方案,在这个属性的上面加了一个Obsolete标签,并说明在Version9.0的时候会去掉,所以后面我们也是需要去显式去添加映射关系。
/// <summary>
/// Create missing type maps during mapping, if necessary
/// </summary>
[Obsolete("Support for automatically created maps will be removed in version 9.0. You will need to explicitly configure maps, manually or using reflection. Also consider attribute mapping (http://docs.automapper.org/en/latest/Attribute-mapping.html).")]
bool ? CreateMissingTypeMaps { get; set; }
3 部分对象的忽略
有的时候我们将源映射到目标的时候,希望忽略掉一些字段的赋值,比如Id,我们希望框架来自动为我们的实体来添加主键Id,那么我们应该怎么处理呢?
public override void Initialize() {
IocManager.RegisterAssemblyByConvention(typeof(DcsApplicationModule).GetAssembly());
Configuration.Modules.AbpAutoMapper().Configurators.Add(config => {
config.CreateMissingTypeMaps = true;
config.CreateMap<VehicleSoldDto, VehicleSold>(MemberList.Source)
.ForMember(d => d.Id, o => o.Ignore());
});
}
3 ProjectTo方法
AutoMapper为我们提供了一个IQueryable类型的扩展,能够很方便的让我们进行关系之间的映射,我们来看看具体的源码,然后再看看在具体的项目中是如何使用的?
/// <summary>
/// Extension method to project from a queryable using the provided mapping engine
/// </summary>
/// <remarks>Projections are only calculated once and cached</remarks>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Queryable source</param>
/// <param name="configuration">Mapper configuration</param>
/// <param name="membersToExpand">Explicit members to expand</param>
/// <returns>Expression to project into</returns>
public static IQueryable<TDestination> ProjectTo<TDestination>(
this IQueryable source,
IConfigurationProvider configuration,
params Expression<Func<TDestination, object>>[] membersToExpand
)
=> source.ProjectTo(configuration, null, membersToExpand);
这个快捷方法能够让我们不需要通过ObjectMapper.Map方法来快速进行对象之间的映射,这里需要注意的是这时候这两个对象之间也需要在Profile或者是Initialize方法中通过CreateMap来指定映射关系,这里我们来看看在具体的业务中该如何使用。
/// <summary>
/// 查询维修预约单
/// </summary>
/// <param name="input">查询输入</param>
/// <param name="pageRequest">分页输入</param>
/// <returns>带分页的维修预约单信息</returns>
public async Task<Page<QueryRepairAppointmentsOutput>> QueryRepairAppointmentsAsync(QueryRepairAppointmentsInput input, PageRequest pageRequest) {
var queryResults = _repairAppointmentRepository.GetAll()
.Include(a => a.ServiceAdvisor)
.Where(a => a.DealerId == SdtSession.TenantId) // 经销商Id=登录企业Id
.WhereIf(!string.IsNullOrWhiteSpace(input.Code), a => a.Code.Contains(input.Code))
.WhereIf(!string.IsNullOrWhiteSpace(input.Vin), a => a.Vin.Contains(input.Vin))
.WhereIf(!string.IsNullOrWhiteSpace(input.LicensePlate), a => a.LicensePlate.Contains(input.LicensePlate))
.WhereIf(!string.IsNullOrWhiteSpace(input.CustomerName), a => a.CustomerName.Contains(input.CustomerName))
.WhereIf(!string.IsNullOrWhiteSpace(input.ServiceAdvisorName), a => a.ServiceAdvisor.Name.Contains(input.ServiceAdvisorName))
.WhereIf(input.OrderChannel?.Length > 0, a => input.OrderChannel.Contains(a.OrderChannel))
.WhereIf(input.Status?.Length > 0, a => input.Status.Contains(a.Status))
.WhereIf(input.BeginPlanArriveDate.HasValue, a => input.BeginPlanArriveDate.Value <= a.PlanArriveDate)
.WhereIf(input.EndPlanArriveDate.HasValue, a => a.PlanArriveDate <= input.EndPlanArriveDate)
.WhereIf(input.BeginArriveTime.HasValue, a => input.BeginArriveTime <= a.ArriveTime)
.WhereIf(input.EndArriveTime.HasValue, a => a.ArriveTime <= input.EndArriveTime)
.WhereIf(input.BeginCreateTime.HasValue, a => input.BeginCreateTime <= a.CreateTime)
.WhereIf(input.EndCreateTime.HasValue, a => a.CreateTime <= input.EndCreateTime);
var totalCount = await queryResults.CountAsync();
var pagedResults = await queryResults.ProjectTo<QueryRepairAppointmentsOutput>(_autoMapper.ConfigurationProvider)
.PageAndOrderBy(pageRequest).ToListAsync();
return new Page<QueryRepairAppointmentsOutput>(pageRequest, totalCount, pagedResults);
}
这里通过一个ProjectTo<T>的方法就能够实现从源到目标的映射,这里需要注意的是这个方法中的_autoMapper是一个IMapper注入的对象,这个参数的注入到底有什么用呢?具体也不是十分清楚,但是在单元测试中需要添加此参数,这个可以去尝试。
4 AutoMapTo、AutoMapFrom
简单对象之间的映射关系,可以直接通过给类型打标签的方式来进行,这样就不用自己去通过CreateMap来添加映射了。
[AutoMapTo(typeof(User))]
public class CreateUserInput
{
public string Name { get; set; } public string Surname { get; set; } public string EmailAddress { get; set; } public string Password { get; set; }
}
最后,点击这里返回整个ABP系列的主目录。
ABP中的AutoMapper的更多相关文章
- 说说ABP项目中的AutoMapper,Castle Windsor(痛并快乐着)
这篇博客要说的东西跟ABP,AutoMapper和Castle Windsor都有关系,而且也是我在项目中遇到的问题,最终解决了,现在的感受就是“痛并快乐着”. 首先,这篇博客不是讲什么新的知识点,而 ...
- 在ABP中灵活使用AutoMapper
demo地址:ABP.WindowsService 该文章是系列文章 基于.NetCore和ABP框架如何让Windows服务执行Quartz定时作业 的其中一篇. AutoMapper简介 Auto ...
- ABP源码分析二:ABP中配置的注册和初始化
一般来说,ASP.NET Web应用程序的第一个执行的方法是Global.asax下定义的Start方法.执行这个方法前HttpApplication 实例必须存在,也就是说其构造函数的执行必然是完成 ...
- ABP源码分析三十五:ABP中动态WebAPI原理解析
动态WebAPI应该算是ABP中最Magic的功能之一了吧.开发人员无须定义继承自ApiController的类,只须重用Application Service中的类就可以对外提供WebAPI的功能, ...
- ABP源码分析四十七:ABP中的异常处理
ABP 中异常处理的思路是很清晰的.一共五种类型的异常类. AbpInitializationException用于封装ABP初始化过程中出现的异常,只要抛出AbpInitializationExce ...
- ABP中使用Redis Cache(1)
本文将讲解如何在ABP中使用Redis Cache以及使用过程中遇到的各种问题.下面就直接讲解使用步骤,Redis环境的搭建请直接网上搜索. 使用步骤: 一.ABP环境搭建 到http://www.a ...
- ABP中使用Redis Cache(2)
上一篇讲解了如何在ABP中使用Redis Cache,虽然能够正常的访问Redis,但是Redis里的信息无法同步更新.本文将讲解如何实现Redis Cache与实体同步更新.要实现数据的同步更新,我 ...
- ABP中使用OAuth2(Resource Owner Password Credentials Grant模式)
ABP目前的认证方式有两种,一种是基于Cookie的登录认证,一种是基于token的登录认证.使用Cookie的认证方式一般在PC端用得比较多,使用token的认证方式一般在移动端用得比较多.ABP自 ...
- 在Abp中集成Swagger UI功能
在Abp中集成Swagger UI功能 1.安装Swashbuckle.Core包 通过NuGet将Swashbuckle.Core包安装到WebApi项目(或Web项目)中. 2.为WebApi方法 ...
随机推荐
- [树链剖分]BZOJ3589动态树
题目描述 别忘了这是一棵动态树, 每时每刻都是动态的. 小明要求你在这棵树上维护两种事件 事件0: 这棵树长出了一些果子, 即某个子树中的每个节点都会长出K个果子. 事件1: 小明希望你求出几条树枝上 ...
- LDA算法 (主题模型算法) 学习笔记
转载请注明出处: http://www.cnblogs.com/gufeiyang 随着互联网的发展,文本分析越来越受到重视.由于文本格式的复杂性,人们往往很难直接利用文本进行分析.因此一些将文本数值 ...
- 利用JDK方式和GuavaAPI方式实现观察者模式
1.JDK方法实现案例需求: 去餐厅吃饭有时候需要排队,进行排队叫号.假如所有等待的人都是观察者,叫号系统就是一个被监听的主题对象.当叫号系统发出叫号通知后,所有等待的人,都会收到通知,然后检查自己的 ...
- SQL语句简单增删改查
常用数据类型 Int:整数,长度没有作用 Varchar:字符串,varchar(3)表示最多存放3个字符,1个中文或英文或符合都占1个字符 Decimal:小数,decimal(5,2)表示共存5位 ...
- php 将office文件(word/excel/ppt)转化为pdf(windows和linux只要安装对应组件应该就行)
一.配置环境 (1)配置php.ini 添加:extension=php_com_dotnet.dll com.allow_dcom = true // 去掉号,改为true 重启环境 (2) 安装 ...
- 大数据/NoSQL经典电子书pdf下载
Hadoop系列 Cloudera出品的各种官方文档 入门必备 https://www.cloudera.com/documentation.html Cloudera Hadoop大数据平台实战指南 ...
- 经管/管理/团队经典电子书pdf下载
卓有有效的管理者 管理的本质 只有偏执狂才能生存 格鲁夫给经理人的第一课 影响力: 你为什么会说“是” 关键影响力:如何调动团队力量 执行 如何完成任务的学问
- Tosca 添加插件或者是扩展功能,把页面上某块内容识别成table
#遇到了问题 "ICS table was not found" 是因为编辑case的时候用到了插件的功能, 但是setting里面却没有配置这个插件 #在哪里添加插件 #目的 这 ...
- flutter DateTime日期&时间选择器
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'dart:async'; class ...
- Vue路由编程式导航以及hash模式
import Vue from 'vue'; import App from './App.vue'; //引入公共的scss 注意:创建项目的时候必须用scss import './assets/c ...