Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 872
Tarta Avatar asked Nov 11 '16 10:11

Tarta


People also ask

How do I create a map in AutoMapper?

Create a MapperConfiguration instance and initialize configuration via the constructor: var config = new MapperConfiguration(cfg => { cfg. CreateMap<Foo, Bar>(); cfg.

What is AutoMapper in Entity Framework?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.


1 Answers

Try this:

Mapper.CreateMap<EmployeeViewModel, Employee>()
                        .ForMember(d => d.Name, d => d.MapFrom(x => string.Format("{0}{1}", x.Name, x.Surname)));
like image 164
Alex Ovechkin Avatar answered Nov 09 '22 16:11

Alex Ovechkin