.NET CORE 中使用AutoMapper进行对象映射

1、NuGet安装

AutoMapperAutoMapper.Extensions.Microsoft.DependencyInjection

2、新建以下几个文件

a:IProfile

1 namespace DTO.config
2 {
3     public interface IProfile
4     {
5     }
6 }
View Code

b:MapperRegister

 1 namespace DTO.config
 2 {
 3     public static class MapperRegister
 4     {
 5         public static Type[] MapType()
 6         {
 7             var allIem = Assembly
 8                .GetEntryAssembly()
 9                .GetReferencedAssemblies()
10                .Select(Assembly.Load)
11                .SelectMany(y => y.DefinedTypes)
12                .Where(type =>
13                 typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType()));
14             List<Type> allList = new List<Type>();
15             foreach (var typeinfo in allIem)
16             {
17                 var type = typeinfo.AsType();
18                 allList.Add(type);
19             }
20             Type[] alltypes = allList.ToArray();
21             return alltypes;
22         }
23     }
24 }
View Code

c:ConfigProfile

 1 namespace DTO.config
 2 {
 3     public class ConfigProfile : Profile, IProfile
 4     {
 5         public ConfigProfile()
 6         {
 7             Init();
 8 
 9             //单独添加映射
10             //CreateMap<SysAdminDto, SysAdmin>();
11             //CreateMap<SysAdmin, SysAdminDto>();
12 
13         }
14 
15         public static bool HasImplementedRawGeneric([NotNull] Type type, [NotNull] Type generic)
16         {
17             if (type == null || generic == null) return false;
18             var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
19             if (isTheRawGenericType) return true;
20             while (type != null && type != typeof(object))
21             {
22                 isTheRawGenericType = IsTheRawGenericType(type);
23                 if (isTheRawGenericType) return true;
24                 type = type.BaseType;
25             }
26             return false;
27             bool IsTheRawGenericType(Type test)
28                 => generic == (test.IsGenericType ? test.GetGenericTypeDefinition() : test);
29         }
30 
31         //初始化映射,所有实现IDto接口的类
32         void Init()
33         {
34             var nn = typeof(IDto<>).FullName;
35             var types = typeof(IDto<>).Assembly.GetTypes()//获取命名空间的所有类
36                 .Where(t => HasImplementedRawGeneric(t, typeof(IDto<>)))//所有实现IDto泛型接口的类
37                 .Where(t => t.IsClass);//只选择类(排除接口自己)
38 
39             foreach (var dtoType in types)
40             {
41                 var interFaces = dtoType.GetInterfaces();
42                 if (interFaces.Count() > 0)
43                 {
44                     var otherType = interFaces[0].GetGenericArguments()[0];
45                     var dtoMp = CreateMap(dtoType, otherType);
46                     var otherMp = CreateMap(otherType, dtoType);
47 
48                     foreach (var prop in dtoType.GetProperties())
49                     {
50                         var attr = prop.GetCustomAttribute<MapFeildAttribute>();
51                         if (attr != null)
52                         {
53                             dtoMp.ForMember(attr.name, x => x.MapFrom(prop.Name));
54                             otherMp.ForMember(prop.Name, x => x.MapFrom(attr.name));
55                         }
56                     }
57                 }
58             }
59         }
60     }
61 }
View Code

d:AutoMapperHelper

 1 namespace DTO
 2 {
 3     public static class AutoMapperHelper
 4     {
 5         private static IServiceProvider ServiceProvider;
 6         public static void UseStateAutoMapper(this IApplicationBuilder applicationBuilder)
 7         {
 8             ServiceProvider = applicationBuilder.ApplicationServices;
 9         }
10 
11         public static TDestination Map<TDestination>(object source)
12         {
13             var mapper = ServiceProvider.GetRequiredService<IMapper>();
14             return mapper.Map<TDestination>(source);
15         }
16 
17         public static TDestination Map<TSource, TDestination>(TSource source)
18         {
19             var mapper = ServiceProvider.GetRequiredService<IMapper>();
20 
21             return mapper.Map<TSource, TDestination>(source);
22         }
23 
24         public static TDestination MapTo<TSource, TDestination>(this TSource source)
25         {
26             var mapper = ServiceProvider.GetRequiredService<IMapper>();
27             return mapper.Map<TSource, TDestination>(source);
28         }
29 
30         public static TDestination MapTo<TDestination>(this object source)
31         {
32             var mapper = ServiceProvider.GetRequiredService<IMapper>();
33             return mapper.Map<TDestination>(source);
34         }
35 
36         public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
37         {
38             var mapper = ServiceProvider.GetRequiredService<IMapper>();
39             return mapper.Map<List<TDestination>>(source);
40         }
41 
42 
43         public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
44         {
45             var mapper = ServiceProvider.GetRequiredService<IMapper>();
46             return mapper.Map<List<TDestination>>(source);
47         }
48     }
49 }
View Code

e:IDto

1 namespace DTO
2 {
3     public interface IDto<T> where T : class, new()
4     {
5     }
6 }
View Code

f:MapFeildAttribute

 1 namespace DTO.attribute
 2 {
 3     [AttributeUsage(AttributeTargets.Property)]
 4     public class MapFeildAttribute : Attribute
 5     {
 6         public string name;
 7         public MapFeildAttribute(string name)
 8         {
 9             this.name = name;
10         }
11     }
12 }
View Code

3、系统配置

1  public void ConfigureServices(IServiceCollection services)
2         {           
3             //注册automapper
4             services.AddAutoMapper(MapperRegister.MapType());
5         }
View Code
1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2         {           
3             //automapper
4             app.UseStateAutoMapper();
5         }
View Code

4、使用

 1 namespace DTO
 2 {
 3     //继承接口IDto,并传入泛型映射的实体类
 4     public class SysAdminDto : IDto<SysAdmin>
 5     {        
 6         public int id { get; set; }
 7        //使用注解MapFeild指定映射的字段,不指定则默认为字段名相同
 8         [MapFeild("role_type")]
 9         public int RoleType { get; set; } = 0;
10         
11         public int action_auth { get; set; } = 0;
12         
13     }
14 }
1 var sysAdmins= rBase.IQueryable<SysAdmin>().ToList();
2 var sysAdminDtos = list.MapToList<SysAdminDto>();

 

借鉴了很多网友的代码,仅此记录一下

 

posted @ 2020-07-31 15:32  grax  阅读(255)  评论(0编辑  收藏  举报