• .Net Core使用AutoMapper做对象关系映射


    我想很多后端开发者,纠结于如何在Dto及表实体中做属性关系映射,因为真的太繁琐了。,

    ⒈如何使用?

    1             Mapper.Initialize(cfg => cfg.CreateMap<UsersInputDto, Users>());
    2             UsersInputDto input = new UsersInputDto()
    3             {
    4                 id = 1, firstname = "fan", lastname = "qi", uname = "fanqisoft", pwd = "admin", enabled = 1
    5             };
    6             Users user = Mapper.Map<Users>(input);

    ⒉映射前或映射后进行操作

      首先附上实体类

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace AutoMapperTest.Entities
     6 {
     7     public class Users
     8     {
     9         public int id { get; set; }
    10         public string fullname { get; set; }
    11         public int? age { get; set; }
    12         public string username { get; set; }
    13 
    14         public string password { get; set; }
    15         public int? enabled { get; set; }
    16 
    17         public override string ToString()
    18         {
    19             return $"用户ID:{this.id} 
    用户姓名:{this.fullname}
    用户名:{this.username} 
    用户密码:{this.password} 
    用户是否启用:{(this.enabled==1?'是':'否')}";
    20         }
    21     }
    22 }

      InputDto

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Text;
     4 
     5 namespace AutoMapperTest.Entities
     6 {
     7     public class UsersInputDto
     8     {
     9         public int id { get; set; }
    10         public string firstname { get; set; }
    11         public string lastname { get; set; }
    12         public int? age { get; set; }
    13         public string uname { get; set; }
    14 
    15         public string pwd { get; set; }
    16         public int? enabled { get; set; }
    17     }
    18 }

      

      当前端InputDto传到后端时,我需要将Dto中的firstname及lastname合并转换为数据表中的fullname

    1             Mapper.Initialize(cfg => 
    2             {
    3                 cfg.CreateMap<UsersInputDto, Users>().BeforeMap((dto, ent) => ent.fullname = dto.firstname + "_" + dto.lastname);
    4             });

    ⒊条件映射,必须必要的条件后才会映射属性。

    1             Mapper.Initialize(cfg => 
    2             {
    3                 cfg.CreateMap<UsersInputDto, Users>().ForMember(d => d.age, u => u.Condition(s => s.age >= 0 && s.age <= 120));
    4             });

    ⒋属性对应映射,Dto中属性名  != 数据表属性名

    1             Mapper.Initialize(cfg => 
    2             {
    3                 cfg.CreateMap<UsersInputDto, Users>().ForMember(d => d.username, u => u.MapFrom(s => s.uname))
    4                                                      .ForMember(d => d.password, u => u.MapFrom(s => s.pwd)); 
    5             });

    ⒌使用配置文件?实现Profile类并在构造器中初始化你的配置。

     1 using AutoMapper;
     2 using AutoMapperTest.Entities;
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Text;
     6 
     7 namespace AutoMapperTest.AutoMapper
     8 {
     9     public class AutoMapperConfig:Profile
    10     {
    11         public AutoMapperConfig()
    12         {
    13             CreateMap<UsersInputDto, Users>();
    14         }
    15     }
    16 }
    1             Mapper.Initialize(cfg => 
    2             {
    3                 cfg.CreateMap<UsersInputDto, Users>().ForMember(d => d.username, u => u.MapFrom(s => s.uname))
    4                                                      .ForMember(d => d.password, u => u.MapFrom(s => s.pwd));
    5                 cfg.AddProfile<AutoMapperConfig>();   //添加一个配置文件
    6             });

    ⒍Dto中数据类型和数据表不一致那就自定义转换器吧。

     1 using AutoMapper;
     2 using AutoMapperTest.Entities;
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Text;
     6 
     7 namespace AutoMapperTest.AutoMapper
     8 {
     9     public class UsersConverter:ITypeConverter<Users,UsersOutputDto>
    10     {
    11         public UsersOutputDto Convert(Users source, UsersOutputDto destination, ResolutionContext context)
    12         {
    13             string[] names = source.fullname.Split("_");
    14             return new UsersOutputDto()
    15             {
    16                 id = source.id,
    17                 firstname = names[0],
    18                 lastname = names[1]
    19             };
    20         }
    21     }
    22 }
    1             Mapper.Initialize(cfg =>
    2             {
    3                 cfg.CreateMap<Users, UsersOutputDto>().ConvertUsing<UsersConverter>();
    4             });
    5             Users users = new Users()
    6             {
    7                 id = 1, fullname = "fan_qi",age = 25,username = "fanqisoft",password ="admin",enabled = 1
    8             };
    9             UsersOutputDto output = Mapper.Map<UsersOutputDto>(users);

     ⒎附一个可用的静态工具类

     1 using AutoMapper;
     2 using System;
     3 using System.Collections;
     4 using System.Collections.Generic;
     5 using System.Data;
     6 using System.Text;
     7 
     8 namespace AutoMapperTest.AutoMapper
     9 {
    10     /// <summary>
    11     /// AutoMapper扩展帮助类
    12     /// </summary>
    13     public static class AutoMapperHelper
    14     {
    15         /// <summary>
    16         /// 类型映射
    17         /// </summary>
    18         /// <typeparam name="T"></typeparam>
    19         /// <param name="obj"></param>
    20         /// <returns></returns>
    21         public static T MapTo<T>(this object obj)
    22         {
    23             if(obj == null)
    24             {
    25                 return default(T);
    26             }
    27             Mapper.Initialize(cfg =>
    28             {
    29                 cfg.CreateMap(obj.GetType(), typeof(T));
    30             });
    31             return Mapper.Map<T>(obj);
    32         }
    33 
    34         /// <summary>
    35         /// 集合列表类型映射
    36         /// </summary>
    37         public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
    38         {
    39             foreach (var first in source)
    40             {
    41                 var type = first.GetType();
    42                 Mapper.Initialize(cfg =>
    43                 {
    44                     cfg.CreateMap(type, typeof(TDestination));
    45                 });
    46                 break;
    47             }
    48             return Mapper.Map<List<TDestination>>(source);
    49         }
    50         /// <summary>
    51         /// 集合列表类型映射
    52         /// </summary>
    53         public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
    54         {
    55             //IEnumerable<T> 类型需要创建元素的映射
    56             Mapper.Initialize(cfg =>
    57             {
    58                 cfg.CreateMap<TSource, TDestination>();
    59             });
    60             return Mapper.Map<List<TDestination>>(source);
    61         }
    62         /// <summary>
    63         /// 类型映射
    64         /// </summary>
    65         public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
    66                     where TSource : class
    67                     where TDestination : class
    68         {
    69             if (source == null) return destination;
    70             Mapper.Initialize(cfg =>
    71             {
    72                 cfg.CreateMap<TSource, TDestination>();
    73             });
    74             return Mapper.Map(source, destination);
    75         }
    76         /// <summary>
    77         /// DataReader映射
    78         /// </summary>
    79         public static IEnumerable<T> DataReaderMapTo<T>(this IDataReader reader)
    80         {
    81             Mapper.Reset();
    82             Mapper.Initialize(cfg =>
    83             {
    84                 cfg.CreateMap<IDataReader, IEnumerable<T>>();
    85             });
    86             return Mapper.Map<IDataReader, IEnumerable<T>>(reader);
    87         }
    88     }
    89 }

      

  • 相关阅读:
    awk
    django教材
    saltstack的安装过程
    OPENSTACK学习笔记(1)
    5G核心网架构
    内存采集
    分析CPU文件
    环境管理系统
    属性的两种定义方式
    Python 面向对象(初级篇)
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/10798007.html
Copyright © 2020-2023  润新知