【问题标题】:Automapper for DTO to DomainDTO 到域的自动映射器
【发布时间】:2014-02-23 13:32:36
【问题描述】:

我有这样的域名

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

该人的 Gender 属性是查找...这意味着用户从 UI 中选择 Gender 作为下拉列表

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

那么我如何设置我的 AutoMapper... 将 DTO 转换为域,反之亦然?

【问题讨论】:

    标签: ef-code-first automapper code-first dto


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多