Tarta
Tarta

Reputation: 2061

Custom mapping with Automapper where a field in destination is the concatenation of two fields in source

I think that the title already quite explains the problem. I have a source type:

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

and

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

I want to use automapper to convert from EmployeeViewModel to Employee and the name of Employee is the concatenation of name and surname in EmployeeViewModel.

May you kindly explain me how to set the MapperConfiguration? Thanks!

Upvotes: 8

Views: 6158

Answers (1)

Alex Ovechkin
Alex Ovechkin

Reputation: 820

Try this:

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

Upvotes: 15

Related Questions