AutoMapper映射自定义类型 电脑版发表于:2021/6/15 15:39 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#AutoMapper映射自定义类型 [TOC] >枚举 ```csharp public class UserState : Enumeration { public static readonly UserState Start = new UserState(0, "Start"); public static readonly UserState Stop = new UserState(1, "Stop"); protected UserState() { } protected UserState(int value, string displayName) : base(value, displayName) { } } ``` >实体 ```csharp public class RoleRequestDTO { public string Id { get; set; } public string rolename { get; set; } public int status { get; set; } } ``` ```csharp public class RoleDOModel { public RoleDOModel() { } public RoleDOModel(string _Id, string _rolename, RoleStatus _status) { this.Id = _Id; this.rolename = _rolename; this.status = _status; } public string Id { get; set; } public string rolename { get; set; } public RoleStatus status { get; set; } } ``` ```csharp public class RoleDOModel { public RoleDOModel() { } public RoleDOModel(string _Id, string _rolename, RoleStatus _status) { this.Id = _Id; this.rolename = _rolename; this.status = _status; } public string Id { get; set; } public string rolename { get; set; } public RoleStatus status { get; set; } } ``` >测试 ```csharp RoleStatus convertRoleStatus(int status) { var value = status == 0 ? RoleStatus.Start : RoleStatus.Stop; return value; } ``` ```csharp var config = new MapperConfiguration(cfg => { cfg.CreateMap<RoleRequestDTO, RoleDOModel>() // 映射字段 .ForMember(x => x.status, opt => opt.MapFrom(src => convertRoleStatus(src.status))) // 自定义转换 .ConstructUsing(src => new RoleDOModel(src.Id, src.rolename, convertRoleStatus(src.status))) // 反向映射 .ReverseMap() // 自定义转换 .ConvertUsing(src => new RoleRequestDTO() { Id = src.Id, status = src.status.Value ,rolename = src.rolename }) ; }); config.AssertConfigurationIsValid(); var mapper = new Mapper(config); RoleRequestDTO role = new RoleRequestDTO { rolename = "hh", status = 1 }; RoleDOModel rdo = mapper.Map<RoleRequestDTO, RoleDOModel>(role); RoleRequestDTO dto = mapper.Map<RoleDOModel, RoleRequestDTO>(rdo); ```