Home > Software design >  How can I map a object to list of objects in AutoMapper?
How can I map a object to list of objects in AutoMapper?

Time:12-18

I wanna map Person to List of Client with AutoMapper:

and this is my models :



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 Member
{
 public Guid Id { get; set;}
 public string FullName { get; set; }
}

public class Client
{
    public Member User { get; set; }
}

I tried do it with AutoMapper but I couldn't:

CreateMap<Person, List<Client>>();

CodePudding user response:

You need 4 mapping rules:

  1. Map Person to Member.

  2. Map Member to Client.

  3. Map Person to Client.

  4. Map Person to List<Client>.

CreateMap<Person, Member>()
    .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));
                                                                  
CreateMap<Member, Client>()
    .ForMember(dest => dest.User, opt => opt.MapFrom(src => src));
                                                                  
CreateMap<Person, Client>()
    .ConvertUsing((src, dest, ctx) => new Client { User = ctx.Mapper.Map<Member>(src) });
                                                                  
CreateMap<Person, List<Client>>()
    .ConvertUsing((src, dest, ctx) => new List<Client> { ctx.Mapper.Map<Client>(src) });

Demo @ .NET Fiddle

CodePudding user response:

You can map them using the following code:

CreateMap<Person, Client>()
    .ForMember(dest => dest.User, opt => opt.MapFrom(src => new Member { Id = src.Id, FullName = src.Name }));
CreateMap<Person, List<Client>>()
    .ConvertUsing(src => src.Select(x => new Client { User = new Member { Id = x.Id, FullName = x.Name } }).ToList());
  • Related