7

I have a domain and entity class the looks like this:

public class DomainUser
{
    public string Username {get;set;}
    public IList<string> PhoneNumbers {get;set;}
}

public class EntityUser
{
    public string Name {get;set;}
    public IList<Phone> PhoneNumbers {get;set;}
}
public class Phone
{
    public int Id {get;set;}
    public string PhoneNumber {get;set;}
}

I'm trying to map the DomainUser to EntityUser with Automapper. But I don't know how to map from IList<string> to IList<Phone> and fill the PhoneNumer property.

My CreateMap looks like this:

Config.CreateMap<DomainUser, EntityUser>()
    .ForMember(dest => dest.Username, opts => opts.MapFrom(src => src.Username)
    .ForMember(entity => entity.PhoneNumbers.Select(x => x.PhoneNumber), opts => opts.MapFrom(domain => domain.PhoneNumbers) // This doesn't work, but hopefully shows what I'm trying to achieve

How can I solve this issue with AutoMapper?

0

2 Answers 2

6

Here you have the running sample:

Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<string, Phone>().ForMember(dest => dest.PhoneNumber, m => m.MapFrom(src => src)); // <-- important line!
            cfg.CreateMap<DomainUser, EntityUser>()
                .ForMember(dest => dest.Name, m => m.MapFrom(src => src.Username))
                .ForMember(dest => dest.PhoneNumbers, m => m.MapFrom(src => src.PhoneNumbers));
        });
        DomainUser du = new DomainUser {PhoneNumbers = new List<string> {"123", "1234", "12345"}};
        EntityUser eu = Mapper.Map<DomainUser, EntityUser>(du);
Sign up to request clarification or add additional context in comments.

Comments

1

The solution would be:

Config.CreateMap<string, Phone>()
    .ConstructUsing(str => new Phone{ PhoneNumber = str });
Config.CreateMap<DomainUser, EntityUser>();

Originally answered here: https://stackoverflow.com/a/28131572/12959213

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.