在实际的业务环境中,我们的TIn类和TOut类的字段不可能一对一的匹配,这个时候我们就需要来指定他们的实际映射关系。
扩展帮助类对象:
/// <summary>/// AutoMapper扩展类/// </summary>public static class AutoMapperExtension{/// <summary>/// 对象映射/// </summary>public static TOut MapTo<TIn, TOut>(this TIn source){if (source == null) return default(TOut);var config = new MapperConfiguration(cfg => cfg.CreateMap<TIn, TOut>());var mapper = config.CreateMapper();return mapper.Map<TOut>(source);}/// <summary>/// 对象映射(自定义)/// </summary>public static TOut MapTo<TIn, TOut>(this TIn source, Profile profile){if (source == null) return default(TOut);var config = new MapperConfiguration(cfg => cfg.AddProfile(profile));var mapper = config.CreateMapper();return mapper.Map<TOut>(source);}/// <summary>/// 集合映射/// </summary>/// <typeparam name="TSource"></typeparam>/// <typeparam name="TDestination"></typeparam>/// <param name="source"></param>/// <returns></returns>public static IEnumerable<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source){if (source == null) return new List<TDestination>();var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());var mapper = config.CreateMapper();return mapper.Map<List<TDestination>>(source);}/// <summary>/// 集合映射(自定义)/// </summary>/// <typeparam name="TSource"></typeparam>/// <typeparam name="TDestination"></typeparam>/// <param name="source"></param>/// <param name="profile"></param>/// <returns></returns>public static IEnumerable<TDestination> MapToList<TSource, TDestination >(this IEnumerable<TSource> source, Profile profile) {if (source == null) return new List<TDestination>();var config = new MapperConfiguration(cfg => cfg.AddProfile(profile));var mapper = config.CreateMapper();return mapper.Map<List<TDestination>>(source);}}
自定义转换:
- 扩展自定义转换对象
/// <summary>/// 将DBUser实体转换为DBUserMemberDto/// </summary>public class UserTestMember: Profile{/// <summary>/// 将DBUser实体转换为DBUserMemberDto/// </summary>public UserTestMember(){CreateMap<DBUser, DBUserMemberDto>().ForMember(dto => dto.Id, opt => opt.MapFrom(info => info.Id)).ForMember(dto => dto.Name, opt => opt.MapFrom(info => info.Name)).ForMember(dto => dto.Sex, opt => opt.MapFrom(info => info.Sex ? "男" : "女"));}}
该字段对应源不存在时可以选择用其他字段代替或者忽略改字段的映射
CreateMap<DBUser, DBUserMemberDto>().ForMember(dto => dto.Id, opt => opt =>opt.Ignore());
- 使用方法(user是数据查询出来的DBUser):
user.MapTo<DBUser, DBUserMemberDto>(new UserTestMember());