鉴于以下课程,我需要建立从人到 PersonDTO 的映射。我遇到的问题是PersonDTO的地址字段映射没有发生。
public class Address
{
public int Id { get; set; }
public string Value { get; set; }
}
public class RegisteredAddresses
{
public int Id { get; set; }
public List<Address> Addresses { get; set; }
public RegisteredAddresses()
{
this.Addresses = new List<Address>();
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public List<RegisteredAddresses> AddressGroups { get; set; }
public Person()
{
this.AddressGroups = new List<RegisteredAddresses>();
}
}
public class PersonDTO
{
public string Name { get; set; }
public List<Address> Addresses { get; set; }
public PersonDTO()
{
this.Addresses = new List<Address>();
}
}
class Program
{
static void Main(string[] args)
{
RegisteredAddresses registeredAddresses1 = new RegisteredAddresses();
RegisteredAddresses registeredAddresses2 = new RegisteredAddresses();
Person person = new Person();
registeredAddresses1.Addresses.Add(new Address { Id = 1, Value = "address 1" });
registeredAddresses1.Addresses.Add(new Address { Id = 2, Value = "address 2" });
registeredAddresses1.Addresses.Add(new Address { Id = 3, Value = "address 3" });
registeredAddresses1.Addresses.Add(new Address { Id = 4, Value = "address 4" });
registeredAddresses1.Addresses.Add(new Address { Id = 5, Value = "address 5" });
registeredAddresses2.Addresses.Add(new Address { Id = 1, Value = "address A" });
registeredAddresses2.Addresses.Add(new Address { Id = 2, Value = "address B" });
registeredAddresses2.Addresses.Add(new Address { Id = 3, Value = "address C" });
registeredAddresses2.Addresses.Add(new Address { Id = 4, Value = "address D" });
registeredAddresses2.Addresses.Add(new Address { Id = 5, Value = "address E" });
person.Name = "person 1";
person.AddressGroups.Add(registeredAddresses1);
person.AddressGroups.Add(registeredAddresses2);
Mapper.CreateMap<Person, PersonDTO>();
// after this line....
var personDto = Mapper.Map<Person, PersonDTO>(person);
// .... personDTO.Addresses.Count() is zero; where it should be 10
}
}
答案 0 :(得分:2)
您需要告诉AutoMapper如何将AddressGroups
中包含的地址映射到PersonDTO
中的地址。类似的东西:
Mapper.CreateMap<Person, PersonDTO>()
.ForMember(pd => pd.Addresses,
opt => opt.ResolveUsing(p => p.AddressGroups
.SelectMany(ra => ra.Addresses)
)
);