Automapper - 将属性映射到集合

时间:2017-09-27 18:28:47

标签: c# automapper automapper-5

源类:

public class ApplicationDriverFormVM
{
    public ApplicationDriverAddressFormVM PresentAddress { get; set; }
    public List<ApplicationDriverAddressFormVM> PreviousAddresses { get; set; }
}

public class ApplicationDriverAddressFormVM
{
    [Required]
    [StringLength(256)]
    [Display(Name = "Address")]
    public string Address { get; set; }
    [Required]
    [StringLength(256)]
    [Display(Name = "City")]
    public string City { get; set; }
    //.....
}

目的地课程:

public class ApplicationDriverDomain
{
    public List<ApplicationDriverAddressDomain> Addresses { get; set; }
}

public class ApplicationDriverAddressDomain
{
    public int Id { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    //....
    public bool IsPresentAddress { get; set; }
}

所以,我想将PresentAddress(一个对象)和PreviousAddresses(集合)映射到Addresses属性(集合),其中每个元素都有IsPresentAddress属性,如果它映射了PresentAddress,则它应该为true,而对于PreviousAddresses映射元素则为false。我尝试编写这样的地图基本规则:

        CreateMap<ViewModels.ApplicationDriverFormVM, ApplicationDriverDomain>();
        CreateMap<ViewModels.ApplicationDriverAddressFormVM, ApplicationDriverAddressDomain>();

当然,它无法正常工作。怎么做?

1 个答案:

答案 0 :(得分:2)

可以使用ForMember扩展方法完成此操作。

这是一种快速而肮脏的方式来获得你想要的东西。它创建了一个新的ApplicationDriverAddressFormVM组合列表来映射,但是如果你浏览文档,你可能会找到更优雅的东西。

Mapper.CreateMap<ApplicationDriverFormVM, ApplicationDriverDomain>()
    .ForMember(dest => dest.Addresses, opt => opt.MapFrom(src => src.PreviousAddresses.Union(new List<ApplicationDriverAddressFormVM>() { src.PresentAddress })));

Mapper.CreateMap<ApplicationDriverAddressFormVM, ApplicationDriverAddressDomain>();

经过进一步调查,我发现了以下方法。它使用ResolveUsing选项。同样,这很粗糙,只使用我发现的第一个功能。您应该进一步探索IMemberConfigurationExpression界面,看看您有哪些其他选项

        Mapper.CreateMap<ApplicationDriverFormVM, ApplicationDriverDomain>()
            .ForMember(dest => dest.Addresses, opt => opt.ResolveUsing(GetAddresses));

...

    static object GetAddresses(ApplicationDriverFormVM src)
    {
        var result = Mapper.Map<List<ApplicationDriverAddressDomain>>(src.PreviousAddresses);
        foreach(var item in result)
        {
            item.IsPresentAddress = false;
        }
        var present = Mapper.Map<ApplicationDriverAddressDomain>(src.PresentAddress);
        present.IsPresentAddress = true;
        result.Add(present);

        return result;
    }