175

I am a newbie to the Automapper framework. I have a domain class and a DTO class as follows:

public class Employee
{
   public long Id {get;set;}
   public string Name {get;set;}
   public string Phone {get;set;}
   public string Fax {get;set;}
   public DateTime DateOfBirth {get;set;}
}

public class EmployeeDto
{
   public long Id {get;set;}
   public string FullName {get;set;}
   public DateTime DateOfBirth {get;set;}
}

Note: The name of property "Name" of Employee class is not the same as that of property "FullName" of EmployeeDto class.

And here's the code to map the Employee object to EmployeeDto:

Mapper.CreateMap<Employee, EmployeeDto>(); // code line (***)
EmployeeDto dto = Mapper.Map<Employee, EmployeeDto>(employee); 

My question is: If I want to map Employee (source class) to EmployeeDto (destination class), how can I specify the mapping rule? In other words, how should I do more with code line (***) above?

4

4 回答 4

345

没关系,我自己找到了解决方案:

Mapper.CreateMap<Employee, EmployeeDto>()
    .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));
于 2013-02-08T17:43:47.320 回答
14

只是将上面的评论滚动到使用 Automapper 8.1+ 的更新方法中......

var mapConfig = new MapperConfiguration(
   cfg => cfg.CreateMap<Employee, EmployeeDto>()
      .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
);

然后您将使用 mapConfig 构建映射器:

var mapper = mapConfig.CreateMapper();
于 2019-07-29T16:09:43.643 回答
8

我们还可以在 Class 属性上指定用于映射

来自https://docs.automapper.org/en/stable/Conventions.html#attribute-support

属性支持

AddMemberConfiguration().AddName<SourceToDestinationNameMapperAttributesMember>(); * 当前始终开启

查找属性/字段的 SourceToDestinationMapperAttribute 实例并调用用户定义的 isMatch 函数来查找成员匹配项。

MapToAttribute 是其中之一,它将根据提供的名称匹配属性。

public class Foo
{
    [MapTo("SourceOfBar")]
    public int Bar { get; set; }
}
于 2020-03-13T15:30:51.117 回答
3

考虑到我们有两个类

public class LookupDetailsBO
    {
        public int ID { get; set; }

        public string Description { get; set; }

    }

另一类是

public class MaterialBO
    {
        [MapTo(nameof(LookupDetailsBO.ID))]
        public int MaterialId { get; set; }

        [MapTo(nameof(LookupDetailsBO.Description))]
        public string MaterialName { get; set; }

        public int LanguageId { get; set; }
    }

通过这种方式,您通常可以知道您遵循哪个属性。并且您确保命名约定,因此如果您更改了源中的属性名称。MapTo ()会提示错误

于 2020-08-03T07:28:05.160 回答