0

I'm new to the whole Automapper world in .net core 3.1 and was going through the docs and SO, but couldnt' find anything for my use case from their latest version 8.0.

Borrowing from another SO post, how could I do this in the new v8.0 configuration?

public class People {
   public string FirstName {get;set;}
   public string LastName {get;set;}
}

public class Phone {
   public string Number {get;set;}
}

Convert to a PeoplePhoneDto like this:

public class PeoplePhoneDto {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string PhoneNumber {get;set;}
}

Would I use still do this?

Mapper.CreateMap<People, PeoplePhoneDto>();
Mapper.CreateMap<Phone, PeoplePhoneDto>()
        .ForMember(d => d.PhoneNumber, a => a.MapFrom(s => s.Number));

1 Answers1

1

Here is a working demo like below:

Model:

public class People
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Phone
{
    public string Number { get; set; }
}

public class PeoplePhoneDto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
}

AutoMapper profile:

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        CreateMap<People, PeoplePhoneDto>();
        CreateMap<Phone, PeoplePhoneDto>()
             .ForMember(d => d.PhoneNumber, a => a.MapFrom(s => s.Number));
    }
}

Startup.cs:

services.AddAutoMapper(typeof(AutoMapperProfile));

Controller:

public class HomeController : Controller
{
    private readonly IMapper _mapper;
   
    public HomeController(IMapper mapper)
    {
        _mapper = mapper;
    }
    public IActionResult Index()
    {
        var people = new People() { FirstName = "aaa", LastName = "bbb" };
        var phone = new Phone() { Number = "12345" };
        var model = _mapper.Map<PeoplePhoneDto>(people); // map dto1 properties
        _mapper.Map(phone, model);

        //do your stuff...
        return View();
    }
}

Result: enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72