不,您必须为配置中的每个 DTO 创建一个映射。
假设你有一个Person.cs
, Address.cs
,Car
和 User 在你的Entities
public class User
{
public int UserId {get;set;}
public string UserName {get;set;}
public PersonDTO Person {get;set;}
}
public class Person
{
public int PersonID {get;set;}
public string Name {get;set;}
public Address Address {get;set;}
public Car Car {get; set;}
}
所以你也有PersonDTO
, AddressDTO
, 和CarDTO
例如
public class UserDTO
{
public int UserId {get;set;}
public string UserName {get;set;}
// HERE IF YOU HAVE:
// public PersonDTO MyPerson {get;set;}
// IT WILL NOT MAP
// Property Names should match
public PersonDTO Person {get;set;}
}
public class PersonDTO
{
public int PersonID {get;set;}
public string Name {get;set;}
public AddressDTO Address {get;set;}
public CarDTO Car {get;set;}
}
您定义了所有映射的类。
public class MapperConfig
{
public static void CreateMappings()
{
Mapper.CreateMap<UserDTO, Entities.User>().ReverseMap();
Mapper.CreateMap<PersonDTO, Entities.Person>().ReverseMap();
Mapper.CreateMap<AddressDTO, Entities.Address>().ReverseMap();
Mapper.CreateMap<CarDTO, Entities.Car>().ReverseMap();
}
}
然后在你的代码中:
UserDTO user = Mapper.Map<UserDTO>(context.Users.First(s => s.UserId == 1));
映射列表:
List<UserDTO> users = Mapper.Map<IEnumerable<UserDTO>>(context.Users).ToList();
只要属性的名称相同,它们就应该映射。