Reputation: 47
Followed the steps mentioned in Automapper wiki to configure nested mapping with complex objects. but not working :
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; }
}
Configuration :
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>();
Execution :
Student student = new Student();
Address add = new Address();
add.Line1 = "abcd";
student.Address = add;
var studentLite = Mapper.Map<StudentDTO>(student);
Although studentDTO is getting mapped properly the AddressDTO is null.
Upvotes: 0
Views: 1911
Reputation: 6023
You're mapping Student.Address
to StudentDTO.AddressDTO
. As the name of your target property has changed, AutoMapper doesn't know what to do with it. If you changed your propertyname in StudentDTO
from AddressDTO
into Address
, Automapper should be able pick it up and map it.
An alternative solution would of course be to instruct AutoMapper explicitly to map Student.Address
to StudentDTO.AddressDTO
.
Upvotes: 3