Home > Software design >  How can I map these classes automapper?
How can I map these classes automapper?

Time:12-18

how can I map Person to Company:

public class Person
{
    public Guid Id { get; set;}
    public string Name { get; set;}
    public string Country { get; set;}
    public string PhoneNumber { get; set;}
}

public class Company
{
    public List<Member> Members { get; set; }
    public string Name { get; set;}
    
}

public class Member
{
 public Guid Id { get; set;}
 public string FullName { get; set; }
}

I tried to do it with auto mapper but I couldn't success .

CodePudding user response:

To map the Person class to the Company class using AutoMapper, you will need to create a mapping configuration that specifies how the properties of the two classes should be mapped.

Here is an example of how you can create the mapping configuration using AutoMapper:

using AutoMapper;

namespace MyProject
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Person, Company>()
                .ForMember(dest => dest.Members, opt => opt.MapFrom(src => new List<Member>
                {
                    new Member
                    {
                        Id = src.Id,
                        FullName = src.Name
                    }
                }))
                .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Country));
        }
    }
}

And you can be using it like this,

public void MapPersonToCompany() {

  var person = new Person {
    Id = Guid.NewGuid(),
      Name = "John Smith",
      Country = "USA",
      PhoneNumber = "123-456-7890"
  };

  var company = _mapper.Map <Company>(person);
}
  • Related