标签 标签 标签

  • 一句话的事儿:

一、最简单的用法

有两个类User和UserDto

  1. public class User
  2. {
  3. public int Id { get; set; }
  4. public string Name { get; set; }
  5. public int Age { get; set; }
  6. }
  7. public class UserDto
  8. {
  9. public string Name { get; set; }
  10. public int Age { get; set; }
  11. }

将User转换成UserDto也和简单

  1. Mapper.Initialize(x => x.CreateMap<User, UserDto>());
  2. User user = new User()
  3. {
  4. Id = 1,
  5. Name = "caoyc",
  6. Age = 20
  7. };
  8. var dto = Mapper.Map<UserDto>(user);

这是一种最简单的使用,AutoMapper会更加字段名称去自动对于,忽略大小写。

二、如果属性名称不同

将UserDto的Name属性改成Name2

  1. Mapper.Initialize(x =>
  2. x.CreateMap<User, UserDto>()
  3. .ForMember(d =>d.Name2, opt => {
  4. opt.MapFrom(s => s.Name);
  5. })
  6. );
  7. User user = new User()
  8. {
  9. Id = 1,
  10. Name = "caoyc",
  11. Age = 20
  12. };
  13. var dto = Mapper.Map<UserDto>(user);

C# AutoMapper 使用方式(03) - 图1

三、使用Profile配置

自定义一个UserProfile类继承Profile,并重写Configure方法

  1. public class UserProfile : Profile
  2. {
  3. protected override void Configure()
  4. {
  5. CreateMap<User, UserDto>()
  6. .ForMember(d => d.Name2, opt =>
  7. {
  8. opt.MapFrom(s => s.Name);
  9. });
  10. }
  11. }

使用时就这样

  1. Mapper.Initialize(x => x.AddProfile<UserProfile>());
  2. User user = new User()
  3. {
  4. Id = 1,
  5. Name = "caoyc",
  6. Age = 20
  7. };
  8. var dto = Mapper.Map<UserDto>(user);

四、空值替换NullSubstitute

空值替换允许我们将Source对象中的空值在转换为Destination的值的时候,使用指定的值来替换空值。

  1. public class UserProfile : Profile
  2. {
  3. protected override void Configure()
  4. {
  5. CreateMap<User, UserDto>()
  6. .ForMember(d => d.Name2, opt => opt.MapFrom(s => s.Name))
  7. .ForMember(d => d.Name2, opt => opt.NullSubstitute("值为空"));
  8. }
  9. }
  1. Mapper.Initialize(x => x.AddProfile<UserProfile>());
  2. User user = new User()
  3. {
  4. Id = 1,
  5. Age = 20
  6. };
  7. var dto = Mapper.Map<UserDto>(user);

结果为:
C# AutoMapper 使用方式(03) - 图2

五、忽略属性Ignore

  1. public class User
  2. {
  3. public int Id { get; set; }
  4. public string Name { get; set; }
  5. public int Age { get; set; }
  6. }
  7. public class UserDto
  8. {
  9. public string Name { get; set; }
  10. public int Age { get; set; }
  11. }
  12. public class UserProfile : Profile
  13. {
  14. protected override void Configure()
  15. {
  16. CreateMap<User, UserDto>().ForMember("Name", opt => opt.Ignore());
  17. }
  18. }

使用

  1. Mapper.Initialize(x => x.AddProfile<UserProfile>());
  2. User user = new User()
  3. {
  4. Id = 1,
  5. Name="caoyc",
  6. Age = 20
  7. };
  8. var dto = Mapper.Map<UserDto>(user);

结果:
C# AutoMapper 使用方式(03) - 图3

六、预设值

如果目标属性多于源属性,可以进行预设值

  1. public class User
  2. {
  3. public int Id { get; set; }
  4. public string Name { get; set; }
  5. public int Age { get; set; }
  6. }
  7. public class UserDto
  8. {
  9. public string Name { get; set; }
  10. public int Age { get; set; }
  11. public string Gender { get; set; }
  12. }
  13. public class UserProfile : Profile
  14. {
  15. protected override void Configure()
  16. {
  17. CreateMap<User, UserDto>();
  18. }
  19. }

使用

  1. Mapper.Initialize(x => x.AddProfile<UserProfile>());
  2. User user = new User()
  3. {
  4. Id = 1,
  5. Name="caoyc",
  6. Age = 20
  7. };
  8. UserDto dto = new UserDto() {Gender = "男"};
  9. Mapper.Map(user, dto);

C# AutoMapper 使用方式(03) - 图4

七、类型转换ITypeConverter

如果数据中Gender存储的int类型,而DTO中Gender是String类型

  1. public class User
  2. {
  3. public int Gender { get; set; }
  4. }
  5. public class UserDto
  6. {
  7. public string Gender { get; set; }
  8. }

类型转换类,需要实现接口ITypeConverter

  1. public class GenderTypeConvertert : ITypeConverter<int, string>
  2. {
  3. public string Convert(int source, string destination, ResolutionContext context)
  4. {
  5. switch (source)
  6. {
  7. case 0:
  8. destination = "男";
  9. break;
  10. case 1:
  11. destination = "女";
  12. break;
  13. default:
  14. destination = "未知";
  15. break;
  16. }
  17. return destination;
  18. }
  19. }

配置规则

  1. public class UserProfile : Profile
  2. {
  3. protected override void Configure()
  4. {
  5. CreateMap<User, UserDto>();
  6. CreateMap<int, string>().ConvertUsing<GenderTypeConvertert>();
  7. //也可以写这样
  8. //CreateMap<int, string>().ConvertUsing(new GenderTypeConvertert());
  9. }
  10. }

使用

  1. Mapper.Initialize(x => x.AddProfile<UserProfile>());
  2. User user0 = new User() { Gender = 0 };
  3. User user1 = new User() { Gender = 1 };
  4. User user2 = new User() { Gender = 2 };
  5. var dto0= Mapper.Map<UserDto>(user0);
  6. var dto1 = Mapper.Map<UserDto>(user1);
  7. var dto2 = Mapper.Map<UserDto>(user2);
  8. Console.WriteLine("dto0:{0}", dto0.Gender);
  9. Console.WriteLine("dto1:{0}", dto1.Gender);
  10. Console.WriteLine("dto2:{0}", dto2.Gender);

结果
C# AutoMapper 使用方式(03) - 图5

八、条件约束Condition
当满足条件时才进行映射字段,例如人类年龄,假设我们现在人类年龄范围为0-200岁(这只是假设),只有满足在这个条件才进行映射
DTO和Entity

  1. public class User
  2. {
  3. public int Age { get; set; }
  4. }
  5. public class UserDto
  6. {
  7. public int Age { get; set; }
  8. }

Profile

  1. public class UserProfile : Profile
  2. {
  3. protected override void Configure()
  4. {
  5. CreateMap<User, UserDto>().ForMember(dest=>dest.Age,opt=>opt.Condition(src=>src.Age>=0 && src.Age<=200));
  6. }
  7. }

使用代码

  1. Mapper.Initialize(x => x.AddProfile<UserProfile>());
  2. User user0 = new User() { Age = 1 };
  3. User user1 = new User() { Age = 150 };
  4. User user2 = new User() { Age = 201 };
  5. var dto0= Mapper.Map<UserDto>(user0);
  6. var dto1 = Mapper.Map<UserDto>(user1);
  7. var dto2 = Mapper.Map<UserDto>(user2);
  8. Console.WriteLine("dto0:{0}", dto0.Age);
  9. Console.WriteLine("dto1:{0}", dto1.Age);
  10. Console.WriteLine("dto2:{0}", dto2.Age);

输出结果
C# AutoMapper 使用方式(03) - 图6

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using AutoMapper;
  7. using System.Data;
  8. namespace ConsoleApplication2
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. //1.普通转换
  15. Name name1 = new Name() { FirstName = "L", LastName = "jz" };
  16. Mapper.CreateMap<Name, NameDto>()
  17. .BeforeMap((name, nameDto) => Console.WriteLine("hello world before"))
  18. .AfterMap((name, nameDto) => Console.WriteLine("hello world after"));
  19. NameDto nameDto1 = Mapper.Map<Name, NameDto>(name1);
  20. Console.WriteLine("1");
  21. Console.WriteLine(nameDto1.FirstName + nameDto1.LastName);
  22. Console.WriteLine();
  23. //Console.ReadKey();
  24. //整体设置
  25. //2.整体即时转换
  26. Mapper.Reset();
  27. Name name2 = new Name() { FirstName = "L", LastName = "jz" };
  28. Mapper.CreateMap<Name, NameDto>()
  29. .ConstructUsing(name => new NameDto() { AllName = name.FirstName + name.LastName });
  30. NameDto nameDto2 = Mapper.Map<Name, NameDto>(name2);
  31. Console.WriteLine("2");
  32. Console.WriteLine(nameDto2.AllName);
  33. Console.WriteLine();
  34. //Console.ReadKey();
  35. //3.整体通过TypeConverter类型转换
  36. Mapper.Reset();
  37. Name name3 = new Name() { FirstName = "L", LastName = "jz" };
  38. Mapper.CreateMap<Name, NameDto>()
  39. .ConvertUsing<NameConverter>();
  40. NameDto nameDto3 = Mapper.Map<Name, NameDto>(name3);
  41. Console.WriteLine("3");
  42. Console.WriteLine(nameDto3.AllName);
  43. Console.WriteLine();
  44. //Console.ReadKey();
  45. //单属性设置
  46. //4.属性条件转换
  47. Mapper.Reset();
  48. Name name4 = new Name() { FirstName = "L", LastName = "jz" };
  49. Mapper.CreateMap<Name, NameDto>()
  50. .ForMember(name => name.FirstName, opt => opt.Condition(name => !name.FirstName.Equals("l", StringComparison.OrdinalIgnoreCase)));
  51. NameDto nameDto4 = Mapper.Map<Name, NameDto>(name4);
  52. Console.WriteLine("4");
  53. Console.WriteLine(string.IsNullOrEmpty(nameDto4.FirstName));
  54. Console.WriteLine();
  55. //Console.ReadKey();
  56. //5.属性忽略
  57. Mapper.Reset();
  58. Name name5 = new Name() { FirstName = "L", LastName = "jz" };
  59. Mapper.CreateMap<Name, NameDto>()
  60. .ForMember(name => name.FirstName, opt => opt.Ignore());
  61. NameDto nameDto5 = Mapper.Map<Name, NameDto>(name5);
  62. Console.WriteLine("5");
  63. Console.WriteLine(string.IsNullOrEmpty(nameDto5.FirstName));
  64. Console.WriteLine();
  65. //Console.ReadKey();
  66. //6.属性转换
  67. Mapper.Reset();
  68. Name name6 = new Name() { FirstName = "L", LastName = "jz" };
  69. Mapper.CreateMap<Name, NameDto>()
  70. .ForMember(name => name.AllName, opt => opt.MapFrom(name => name.FirstName + name.LastName))
  71. .ForMember(name => name.FirstName, opt => opt.MapFrom(name=>name.FirstName));
  72. NameDto nameDto6 = Mapper.Map<Name, NameDto>(name6);
  73. Console.WriteLine("6");
  74. Console.WriteLine(nameDto6.AllName);
  75. Console.WriteLine();
  76. //Console.ReadKey();
  77. //7.属性通过ValueResolver转换
  78. Mapper.Reset();
  79. Name name7 = new Name() { FirstName = "L", LastName = "jz" };
  80. Mapper.CreateMap<Name, StoreDto>()
  81. .ForMember(storeDto => storeDto.Name, opt => opt.ResolveUsing<NameResolver>());
  82. StoreDto store1 = Mapper.Map<Name, StoreDto>(name7);
  83. Console.WriteLine("7");
  84. Console.WriteLine(store1.Name.FirstName + store1.Name.LastName);
  85. Console.WriteLine();
  86. //Console.ReadKey();
  87. //8.属性填充固定值
  88. Mapper.Reset();
  89. Name name8 = new Name() { FirstName = "L", LastName = "jz" };
  90. Mapper.CreateMap<Name, NameDto>()
  91. .ForMember(name => name.AllName, opt => opt.UseValue<string>("ljzforever"));
  92. NameDto nameDto8 = Mapper.Map<Name, NameDto>(name8);
  93. Console.WriteLine("8");
  94. Console.WriteLine(nameDto8.AllName);
  95. Console.WriteLine();
  96. //Console.ReadKey();
  97. //9.属性格式化
  98. Mapper.Reset();
  99. Name name9 = new Name() { FirstName = "L", LastName = "jz" };
  100. Mapper.CreateMap<Name, NameDto>()
  101. .ForMember(name => name.FirstName, opt => opt.AddFormatter<StringFormatter>());
  102. NameDto nameDto9 = Mapper.Map<Name, NameDto>(name9);
  103. Console.WriteLine("9");
  104. Console.WriteLine(nameDto9.FirstName);
  105. Console.WriteLine();
  106. //Console.ReadKey();
  107. //10.属性null时的默认值
  108. Mapper.Reset();
  109. Name name10 = new Name() { FirstName = "L" };
  110. Mapper.CreateMap<Name, NameDto>()
  111. .ForMember(name => name.LastName, opt => opt.NullSubstitute("jz"));
  112. NameDto nameDto10 = Mapper.Map<Name, NameDto>(name10);
  113. Console.WriteLine("10");
  114. Console.WriteLine(nameDto10.LastName);
  115. Console.WriteLine();
  116. //Console.ReadKey();
  117. //其它设置与特性
  118. //11.转换匿名对象
  119. Mapper.Reset();
  120. object name11 = new { FirstName = "L", LastName = "jz" };
  121. NameDto nameDto11 = Mapper.DynamicMap<NameDto>(name11);
  122. Console.WriteLine("11");
  123. Console.WriteLine(nameDto11.FirstName + nameDto11.LastName);
  124. Console.WriteLine();
  125. //Console.ReadKey();
  126. //12.转换DataTable
  127. Mapper.Reset();
  128. DataTable dt = new DataTable();
  129. dt.Columns.Add("FirstName", typeof(string));
  130. dt.Columns.Add("LastName", typeof(string));
  131. dt.Rows.Add("L", "jz");
  132. List<NameDto> nameDto12 = Mapper.DynamicMap<IDataReader, List<NameDto>>(dt.CreateDataReader());
  133. Console.WriteLine("12");
  134. Console.WriteLine(nameDto12[0].FirstName + nameDto12[0].LastName);
  135. Console.WriteLine();
  136. //Console.ReadKey();
  137. //emitMapper error
  138. //List<NameDto> nameDto20 = EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<IDataReader, List<NameDto>>().Map(dt.CreateDataReader());
  139. //13.转化存在的对象
  140. Mapper.Reset();
  141. Mapper.CreateMap<Name, NameDto>()
  142. .ForMember(name => name.LastName, opt => opt.Ignore());
  143. Name name13 = new Name() { FirstName = "L" };
  144. NameDto nameDto13 = new NameDto() { LastName = "jz" };
  145. Mapper.Map<Name, NameDto>(name13, nameDto13);
  146. //nameDto13 = Mapper.Map<Name, NameDto>(name13);//注意,必需使用上面的写法,不然nameDto13对象的LastName属性会被覆盖
  147. Console.WriteLine("13");
  148. Console.WriteLine(nameDto13.FirstName + nameDto13.LastName);
  149. Console.WriteLine();
  150. //Console.ReadKey();
  151. //14.Flatten特性 Store.Name.FirtName=FlattenName.NameFirstname
  152. Mapper.Reset();
  153. Mapper.CreateMap<Store, FlattenName>();
  154. Store store2 = new Store() { Name = new Name() { FirstName = "L", LastName = "jz" } };
  155. FlattenName nameDto14 = Mapper.Map<Store, FlattenName>(store2);
  156. Console.WriteLine("14");
  157. Console.WriteLine(nameDto14.NameFirstname + nameDto14.NameLastName);
  158. Console.WriteLine();
  159. //Console.ReadKey();
  160. //15.将Dictionary转化为对象,现在还不支持
  161. Mapper.Reset();
  162. Mapper.CreateMap<Dictionary<string, object>, Name>();
  163. Dictionary<string, object> dict = new Dictionary<string, object>();
  164. dict.Add("FirstName", "L");
  165. //Name name15 = Mapper.DynamicMap<Dictionary<string, object>, Name>(dict);
  166. Name name15 = Mapper.Map<Dictionary<string, object>, Name>(dict);
  167. Console.WriteLine("15");
  168. Console.WriteLine(name15.FirstName);
  169. Console.WriteLine();
  170. Console.ReadKey();
  171. }
  172. }
  173. public class Store
  174. {
  175. public Name Name { get; set; }
  176. public int Age { get; set; }
  177. }
  178. public class Name
  179. {
  180. public string FirstName { get; set; }
  181. public string LastName { get; set; }
  182. }
  183. public class StoreDto
  184. {
  185. public NameDto Name { get; set; }
  186. public int Age { get; set; }
  187. }
  188. public class NameDto
  189. {
  190. public string FirstName { get; set; }
  191. public string LastName { get; set; }
  192. public string AllName { get; set; }
  193. }
  194. public class FlattenName
  195. {
  196. public string NameFirstname { get; set; }
  197. public string NameLastName { get; set; }
  198. }
  199. public class NameConverter : TypeConverter<Name, NameDto>
  200. {
  201. protected override NameDto ConvertCore(Name source)
  202. {
  203. return new NameDto() { AllName = source.FirstName + source.LastName };
  204. }
  205. }
  206. public class NameResolver : ValueResolver<Name, NameDto>
  207. {
  208. protected override NameDto ResolveCore(Name source)
  209. {
  210. return new NameDto() { FirstName = source.FirstName, LastName = source.LastName,AllName=source.FirstName+source.LastName };
  211. }
  212. }
  213. public class NameFormatter : ValueFormatter<NameDto>
  214. {
  215. protected override string FormatValueCore(NameDto name)
  216. {
  217. return name.FirstName + name.LastName;
  218. }
  219. }
  220. public class StringFormatter : ValueFormatter<string>
  221. {
  222. protected override string FormatValueCore(string name)
  223. {
  224. return name + "-";
  225. }
  226. }
  227. }

  • 本文作者:GeekPower - Felix Sun
  • 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!