ABP中的AutoMapper

论坛 期权论坛 脚本     
已经匿名di用户   2022-7-2 21:50   2814   0

一、什么是AutoMapper

AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another. 
谷歌翻译过来:
AutoMapper是一个简单的小型库,用于解决一个看似复杂的问题 - 摆脱将一个对象映射到另一个对象的代码。

个人理解是一个实例到另一个实例的映射。

使用方法如下

AutoMapper.Mapper.CreateMap<User, UserDto>();
var model = AutoMapper.Mapper.Map<UserDto>(user);

以上代码会根据相同参数名进行映射,如果有额外的要求,如不同参数映射,忽略某个参数,如下

//将User.Role.Id赋值给UserDto.RoleId
public class User
{
public Role Roler;
public long Id;
}
public class UserDto
{
public long RoleId;
public long Id;
}
AutoMapper.Mapper.CreateMap<User, UserDto>().ForMember(dest => dest.RoleId,
opts => opts.MapFrom(src => src.Roler.Id));
//忽略UserDto.Id的映射
CreateMap<User, UserDto>().ForMember(dto => dto.id, opt => opt.Ignore());

假如UserDto中RoleId改为RolerId,则不需要手动设置映射规则也可以自动映射。

映射只需要创建一次

二、在ABP框架中实体之间进行映射有两种办法

1继承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(x => x.LastLoginTime, opt => opt.Ignore());

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

2.创建映射接口,然后在ApplicationModule中的Initialize()进行声明

 internal static class AccuseMapper
    {
        public static void CreateMappings(IMapperConfigurationExpression configuration)
        {
            configuration.CreateMap <Accuse,AccuseListDto>();
            configuration.CreateMap <AccuseListDto,Accuse>();

            configuration.CreateMap <AccuseEditDto,Accuse>();
            configuration.CreateMap <Accuse,AccuseEditDto>();

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

            IocManager.RegisterAssemblyByConvention(thisAssembly);

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

三、MapTo

MapTo是ABP中封装好的方法,根据我们规定的两个实体之间的映射,将值一一映射。null也会被更新到字段中。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP