2014-02-23 68 views
0

我有這樣Automapper的DTO到域

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; } 
} 

域的人的性別屬性是查找...從UI這意味着用戶選擇性別爲下拉

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

那麼如何設置我的AutoMapper ...將DTO轉換爲Domain和反之呢?

回答

1

實際上,AutoMapper提供了開箱即用的對象平鋪功能,所以這個功能會自動爲您完成。

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); 

如果使用常規OuterProperty.InnerProperty在複雜的域對象,類型搭配得當,AutoMapper將在目標對象壓平下降到OuterPropertyInnerProperty。您可以在這裏閱讀所有內容:http://github.com/AutoMapper/AutoMapper/wiki/Flattening

相關問題