C# AutoMapper 使用方法总结

2020-06-15 17:00:09王振洲

如上例,IDEmployeeID 属性名不同,JoinTime JoinYear 不仅属性名不同,属性类型也不同。

var config = new MapperConfiguration(cfg =>
{
 cfg.CreateMap<Employee, EmployeeDto>()
  .ForMember("EmployeeID", opt => opt.MapFrom(src => src.ID))
  .ForMember(dest => dest.EmployeeName, opt => opt.MapFrom(src => src.Name))
  .ForMember(dest => dest.JoinYear, opt => opt.MapFrom(src => src.JoinTime.Year));
});

8 扁平化映射

对象-对象映射的常见用法之一是将复杂的对象模型并将其展平为更简单的模型。

public class Employee
{
 public int ID { get; set; }

 public string Name { get; set; }

 public Department Department { get; set; }
}

public class Department
{
 public int ID { get; set; }

 public string Name { get; set; }
}

public class EmployeeDto
{
 public int ID { get; set; }

 public string Name { get; set; }

 public int DepartmentID { get; set; }

 public string DepartmentName { get; set; }
}

如果目标类型上的属性,与源类型的属性、方法都对应不上,则 AutoMapper 会将目标成员名按驼峰法拆解成单个单词,再进行匹配。例如上例中,EmployeeDto.DepartmentID 就对应到了 Employee.Department.ID。

8.1 IncludeMembers

如果属性命名不符合上述的规则,而是像下面这样:

public class Employee
{
 public int ID { get; set; }

 public string Name { get; set; }

 public Department Department { get; set; }
}

public class Department
{
 public int DepartmentID { get; set; }

 public string DepartmentName { get; set; }
}

public class EmployeeDto
{
 public int ID { get; set; }

 public string Name { get; set; }

 public int DepartmentID { get; set; }

 public string DepartmentName { get; set; }
}

Department 类中的属性名,直接跟 EmployeeDto 类中的属性名一致,则可以使用 IncludeMembers 方法指定。

9 嵌套映射

有时,我们可能不需要展平。看如下例子:

public class Employee
{
 public int ID { get; set; }

 public string Name { get; set; }

 public int Age { get; set; }

 public Department Department { get; set; }
}

public class Department
{
 public int ID { get; set; }

 public string Name { get; set; }

 public string Heads { get; set; }
}

public class EmployeeDto
{
 public int ID { get; set; }

 public string Name { get; set; }

 public DepartmentDto Department { get; set; }
}

public class DepartmentDto
{
 public int ID { get; set; }

 public string Name { get; set; }
}

我们要将 Employee 映射到 EmployeeDto,并且将 Department 映射到 DepartmentDto

var config = new MapperConfiguration(cfg =>
{
 cfg.CreateMap<Employee, EmployeeDto>();
 cfg.CreateMap<Department, DepartmentDto>();
});