سؤال

I have domain like this

 public class Person 
{
    public int id { get; set; }
    public string name { get; set; }
    public Gender gender  { get; set; }
}

public class Gender
{
    public int id { get; set; }
    public string description { get; set; }
}

the Gender property of the person is lookup... which mean from the UI the user select the Gender as drop-down

public class EmployeeDTO
{
    public int personid { get; set; }
    public string name { get; set; }
    public int genderid  { get; set; }
} 

so how do I setup my AutoMapper... to convert the DTO to Domain and vice verse?

هل كانت مفيدة؟

المحلول

Actually, AutoMapper provides object flattening out-of-the-box, so this will be done automatically for you.

Person person = new Person();
Mapper.CreateMap<Person, EmployeeDTO>()
    .ForMember(dest => dest.personid, opt =>
        opt.MapFrom(src => src.id));   // this line is only because I noticed different property names (id vs personid)
EmployeeDTO employeeDTO = Mapper.Map<EmployeeDTO>(person);
employeeDTO.genderid.ShouldEqual(person.gender.id);

If you use the convention OuterProperty.InnerProperty in your complex domain object, and the types match properly, AutoMapper will flatten it down to OuterPropertyInnerProperty in the destination object. You can read all about that here: http://github.com/AutoMapper/AutoMapper/wiki/Flattening

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top