如何指定映射规则,当属性的名称不同 [英] How to specify mapping rule when names of properties differ

查看:426
本文介绍了如何指定映射规则,当属性的名称不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手到Automapper框架。我有一个域类和DTO类,如下所示:

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

注:属性的名称命名员工的类是不相同的财产的全名 EmployeeDto 类。

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

和这里的映射员工<码/ code>对象 EmployeeDto

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



我的问题是:如果我要地图员工(源类) EmployeeDto (目标类),我怎么可以指定映射规则?换句话说,我应该怎么用上面的代码行(***)做多?

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?

推荐答案

没关系,我发现我自己解决办法:

Never mind, I myself found a solution:

Mapper.CreateMap<Employee, EmployeeDto>()
    .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));

这篇关于如何指定映射规则,当属性的名称不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆