AutoMapper 9.0版本
vs2019
引用包
AutoMapper 9.0 AutoMapper.Extensions.Microsoft.DependencyInjection 7.0
准备
数据实体类
public class User { public string Name { get; set; } } public class UserDto { public string Name { get; set; } }
profile配置
public class UserProfile : Profile, IProfile { public UserProfile() { CreateMap<UserDto, User>(); CreateMap<User, UserDto>(); } }
这里的 IProfile 接口,给批量注册用
public interface IProfile { }
配置注册
//方式一:单个注册 services.AddAutoMapper(typeof(UserProfile)); //方式二:多个注册 services.AddAutoMapper(typeof(UserProfile), typeof(UserProfile)); //方式三:批量注册,继承接口IProfile services.AddAutoMapper(typeof(IProfile));
静态方法
public static class AutoMapperHelper { private static IServiceProvider ServiceProvider; public static void UseStateAutoMapper(this IApplicationBuilder applicationBuilder) { ServiceProvider = applicationBuilder.ApplicationServices; } public static TDestination Map<TDestination>(object source) { var mapper = ServiceProvider.GetRequiredService<IMapper>(); return mapper.Map<TDestination>(source); } public static TDestination Map<TSource, TDestination>(TSource source) { var mapper = ServiceProvider.GetRequiredService<IMapper>(); return mapper.Map<TSource, TDestination>(source); } public static TDestination MapTo<TSource, TDestination>(this TSource source) { var mapper = ServiceProvider.GetRequiredService<IMapper>(); return mapper.Map<TSource, TDestination>(source); } public static TDestination MapTo<TDestination>(this object source) { var mapper = ServiceProvider.GetRequiredService<IMapper>(); return mapper.Map<TDestination>(source); } public static List<TDestination> MapToList<TDestination>(this IEnumerable source) { var mapper = ServiceProvider.GetRequiredService<IMapper>(); return mapper.Map<List<TDestination>>(source); } public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source) { var mapper = ServiceProvider.GetRequiredService<IMapper>(); return mapper.Map<List<TDestination>>(source); } }
配置静态方法
app.UseStateAutoMapper();
使用
User user = new User() { Name = "delafqm" }; return user.MapTo<UserDto>();
List<User> users = new List<User>() { new User(){ Name="delafqm1" }, new User(){ Name="delafqm2" }, new User(){ Name="delafqm3" } }; return users.MapToList<UserDto>();
结尾
简单可用配置,其它配置未设置
参考:
https://blog.csdn.net/raphaelhe/article/details/103076371
https://www.cnblogs.com/NCoreCoder/p/11359294.html
https://www.cnblogs.com/NCoreCoder/p/11359294.html