我找不到如何执行此操作的示例。我是AutoMapper的新手。我可能错误地使用了术语。
public class Pet
{
public int petID {get;set;}
public string Name { get; set; }
public string Breed { get; set; }
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Pet> Pets { get; set; }
}
public personVM
{
public string FirstName { get; set; }
public string LastName { get; set; }
List <PetDisplay> PetDisplay {get;set}
}
public PetDisplay
{
int petID {get;set;}
string petDetails {get;set} // This should be a string like Pet.Name & " | " & Pet.Breed
}
如何从人到人的地图?感谢
答案 0 :(得分:0)
您需要设置Person
→personVM
和Pet
→PetDisplay
的映射:
Mapper.CreateMap<Person, personVM>()
.ForMember(dest => dest.PetDisplay, opt => opt.MapFrom(src => src.Pets));
Mapper.CreateMap<Pet, PetDisplay>()
.ForMember(
dest => dest.petDetails,
opt => opt.MapFrom(src => string.Format("{0} | {1}", src.Name, src.Breed)));
使用示例:
var person = new Person
{
FirstName = "Jon",
LastName = "Skeet",
Pets = new List<Pet>
{
new Pet { Breed = "Lab", Name = "Fido" }
}
};
personVM vm = Mapper.Map<personVM>(person);
示例: https://dotnetfiddle.net/eL8VyL
PS:我建议遵循.NET框架命名准则,并对类和成员名称使用PascalCase(PersonVM
而不是personVM
)。