如何使用ABP的Profile类配置AutoMapper自定义映射

一、ABP的Profile有什么用?

Profile用来编写AutoMapper比较复杂的映射规则,在Profile类构造方法中编写的规则最后会配置到AutoMapper中,实现实体到DTO的自动映射。

二、代码浅析

1.ABP模板中,应用层的Module类有一个Initialize方法,该方法中用反射找到所有继承于Profile的类,并添加到映射配置。

public override void Initialize()
{
    var thisAssembly = typeof(EpiApplicationModule).GetAssembly();

    IocManager.RegisterAssemblyByConvention(thisAssembly);

    Configuration.Modules.AbpAutoMapper().Configurators.Add(
        // Scan the assembly for classes which inherit from AutoMapper.Profile
        cfg => cfg.AddMaps(thisAssembly)
    );
}

截图中的注释为ABP模板自带的注释,大意为:扫描该程序集中所有继承于Profile的类。(由于只扫描该程序集,这也是DTO写在应用层的原因之一)

2.继承Profile的例子

public class UserMapProfile : Profile
{
    public UserMapProfile()
    {
        CreateMap<UserDto, User>();
        CreateMap<UserDto, User>()
            .ForMember(x => x.Roles, opt => opt.Ignore())
            .ForMember(x => x.CreationTime, opt => opt.Ignore())
            .ForMember(dto => dto.Timestamp, n => n.MapFrom(entity => entity.CreatorUser.Name + " " +entity.CreationTime.ToString("yyyy年MM月dd日 HH:mm")));

        CreateMap<CreateUserDto, User>();
        CreateMap<CreateUserDto, User>()
        	.ForMember(x => x.Roles, opt => opt.Ignore());
    }
}

构造方法中配置AutoMapper的映射规则,具体配置方法很多博客都有,就不在本文中介绍了。

3.按照以上例子编写好后,UserDto到User、CreateUserDto到User的自动映射就配置好了。一般来说,如果DTO与实体的属性名相同的话,使用【AutoMap】特性就可以了,如果映射规则比较复杂就可以考虑用Profile做自定义映射。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值