什么是AutoMapper

AutoMapper是一个对象与对象的映射器。该映射将一种类型的对象转换为另一种类型的对象。AutoMapper的作用是它通过了一些约定,让人们不用去弄清楚两个对象之间到底是如何转换的。

为什么使用AutoMapper

虽然是在同一程序中,但是程序分层会导致每层关注点不同,从而导致其对象的结构相似而不相同。所以在层与层之间往往需要AutoMapper来转换对象。

举个例子:

域层对象

  1. public class Student{
  2. public int Id { get; set; }
  3. public string Name { get; set; }
  4. public Grade Grade { get; set; }
  5. }
  6. public class Grade {
  7. public int Id { get; set;}
  8. public int GradeNumber { get; set; }
  9. public string GradeName { get { ... } }
  10. public List<Student> Students { get; set; }
  11. }

UI对象

  1. public class StudentDto{
  2. public int Id { get; set; }
  3. public string Name { get; set; }
  4. public StudentGradeDto Grade { get; set; }
  5. }
  6. public class StudentGradeDto{
  7. public int Id { get; set;}
  8. public string GradeName { get; set; }
  9. }

如何使用AutoMapper

首先,你需要源类型和目标类型。当目标类型某个属性和名称与源类型完全相同时,AutoMapper的效果最佳。
然后,你可以使用 MapperConfiguarion 与 CreateMap 来建立映射。通常一个AppDomain只需要一个MapperConfiguration实例,并且在启动时初始化。(每次访问是在创建映射,会影响效率)

  1. var config = new MapperConfiguration(cfg => cfg.CreateMap<Student, StudentDto>());
  2. var mapper = config.CreateMapper(); // or var mapper = new Mapper(config);
  3. StudentDto dto = mapper.Map<StudentDto>(student);

如何测试映射

  1. var config = AutoMapperConfiguration.Configure();
  2. config.AssertConfigurationIsValid();