按照Automapper wiki中提到的步骤配置复杂对象的嵌套映射。但没有工作:
public class Student
{
public int ID{get;set;}
public string Name { get; set; }
public string Standard { get; set; }
public List<string> Course { get; set; }
public int Age { get; set; }
public string FatherName { get; set; }
public string MotherName{ get; set; }
public char Gender { get; set; }
public DateTime DOB { get; set; }
public string BloodGroup { get; set; }
public int TestCondition { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int ID { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Zip { get; set; }
}
DTO:
public class StudentDTO
{
public string Name { get; set; }
public string Standard { get; set; }
public char Gender { get; set; }
public DateTime DOB { get; set; }
public string BG { get; set; }
public int TestCondition { get; set; }
public AddressDTO AddressDTO { get; set; }
}
public class AddressDTO
{
public int ID { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Zip { get; set; }
}
配置:
public class AutoMapperProfileConfig : Profile
{
public AutoMapperProfileConfig()
{
CreateMap<Student, StudentDTO>().ForMember(dest => dest.DOB, opt=>opt.Ignore())
.ForMember(x=>x.BG,opt=>opt.MapFrom(y=>y.BloodGroup))/*.AfterMap((src, dest) => dest.Name = "After MAP")*/
.ForMember(x=>x.TestCondition, opt=>opt.Condition(src => (src.TestCondition >= 100))
);
CreateMap<Address, AddressDTO>();
执行:
Student student = new Student();
Address add = new Address();
add.Line1 = "abcd";
student.Address = add;
var studentLite = Mapper.Map<StudentDTO>(student);
虽然studentDTO正确映射,但AddressDTO为空。
答案 0 :(得分:0)
您将Student.Address
映射到StudentDTO.AddressDTO
。由于目标属性的名称已更改,因此AutoMapper不知道如何处理它。如果您将StudentDTO
中的商家名称从AddressDTO
更改为Address
,则Automapper应该可以将其取出并映射。
另一种解决方案当然是明确指示AutoMapper将Student.Address
映射到StudentDTO.AddressDTO
。