使用AutoMapper将字符串列表映射到对象列表

时间:2018-02-25 14:05:04

标签: c# automapper

我有一个域和实体类,如下所示:

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;}
}

我正在尝试使用Automapper将DomainUser映射到EntityUser。但我不知道如何从IList<string>映射到IList<Phone>并填写PhoneNumer属性。

我的CreateMap看起来像这样:

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

如何使用AutoMapper解决此问题?

1 个答案:

答案 0 :(得分:1)

这里有正在运行的样本:

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);