使用Automapper进行自定义映射,其中目标中的字段是源中两个字段的串联

Tar*_*rta 5 c# converter automapper

我认为这个标题已经很好地解释了这个问题.我有一个源类型:

public class Employee
{
    public string Name { get; set; }
    public string DateOfBirth { get; set; }
    public string srcImage { get; set; }
    public string Email { get; set; }
    public string Role { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

public class EmployeeViewModel
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string DateOfBirth { get; set; }
    public string Email { get; set; }
    public string Role { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想使用automapper从EmployeeViewModel转换为Employee,Employee的名称是EmployeeViewModel中名称姓氏的串联.

请您解释一下如何设置MapperConfiguration?谢谢!

小智 11

试试这个:

Mapper.CreateMap<EmployeeViewModel, Employee>()
                        .ForMember(d => d.Name, d => d.MapFrom(x => string.Format("{0}{1}", x.Name, x.Surname)));
Run Code Online (Sandbox Code Playgroud)