AutoMapper嵌套映射无法正常工作。这是配置和代码:

时间:2017-03-31 09:50:35

标签: c# automapper

按照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为空。

1 个答案:

答案 0 :(得分:0)

您将Student.Address映射到StudentDTO.AddressDTO。由于目标属性的名称已更改,因此AutoMapper不知道如何处理它。如果您将StudentDTO中的商家名称从AddressDTO更改为Address,则Automapper应该可以将其取出并映射。

另一种解决方案当然是明确指示AutoMapper将Student.Address映射到StudentDTO.AddressDTO