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 to do it with AutoMapper but I couldn't:
CreateMap<Person, List<Client>>();
CodePudding user response:
You need 4 mapping rules:
Map
Person
toMember
.Map
Member
toClient
.Map
Person
toClient
.Map
Person
toList<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) });
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());