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方法 ...
随机推荐
- Python里面如何生成随机数?
import randomrandom.random()它会返回一个随机的0和1之间的浮点数
- [HAOI2007][BZOJ 1047]理想的正方形
Description 有一个a*b的整数组成的矩阵,现请你从中找出一个n*n的正方形区域,使得该区域所有数中的最大值和最小值的差最小. Input 第一行为3个整数,分别表示a,b,n的值第二行至第 ...
- hive(3)HiveQL数据定义
HiveQL与传统SQL区别 HiveQL是Hive的查询语言.与mysql的语言最接近,但还是存在于差异性,表现在:Hive不支持行级插入操作.更新操作和删除操作,不支持事物. 基本语法 数据库操作 ...
- 利用Wireshark抓取并分析OpenFlow协议报文
OpenFlow 交换机与控制器交互步骤 1. 利用Mininet仿真平台构建如下图所示的网络拓扑,配置主机h1和h2的IP地址(h1:10.0.0.1,h2:10.0.0.2),测试两台主机之间的网 ...
- Zrender:实现波浪纹效果
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- YARN 状态机可视化,生成状态机图
由于在windows下面,配置好所有 编译hadoop2.4.1源码 的环境会很麻烦,好在我之前已经把hadoop2.4.1的源码成功导入eclipse,并解决了所有错误提示,所以我就可以在eclip ...
- PostgreSQL定时自动备份
PostgreSQL定时自动备份 简介 PostgreSQL数据库中未提供数据库的定时备份功能,所以需要结合备份和定时job功能来共同实现. 这里我选取了2种定时job方式,crontab是Linux ...
- Confluence 实现公司wiki【转】
Confluence是一个企业级的Wiki软件,可用于在企业.部门.团队内部进行信息共享和协同编辑一.安装过程1 安装并配置mysql [root@vm1 ~]# /etc/my.cnf charac ...
- blaze advisor模型部署工具
python信用评分卡建模(附代码,博主录制) https://study.163.com/course/introduction.htm?courseId=1005214003&utm_ca ...
- Flutter AspectRatio、Card 卡片组件
Flutter AspectRatio 组件 AspectRatio 的作用是根据设置调整子元素 child 的宽高比. AspectRatio 首先会在布局限制条件允许的范围内尽可能的扩展,widg ...