自动映射器自定义解析器源成员到目标对象列表映射问题

Auto mapper Custom resolver source members to destination object list mapping issue

场景如下:

源对象:

public class personSrc
{
    public string name {get; set;}
    public string phone {get; set;}
    public string HomeAddress {get; set;}
    public string OfficeAddress {get; set;}
}

目标对象:

public class personDest
{
    public string name {get; set;}
    public string phone {get; set}
    public List<address> addresses {get; set;}
}

public class address
{
    public string location {get; set;}
    public addressType type {get; set;}
}
public enum addressType {Office, Home}

因此,为了将地址成员从源映射到目标,我制作了这个自定义解析器:

public class CustomResolver : IValueResolver<personSrc, personDest, List<address>>
{
  public List<address> Resolve(personSrc source, personDest destination, List<address> destMember, ResolutionContext context)
  {
    List<address> result = new List<adress>();
    if(!String.IsNullOrEmpty(source.HomeAddress))
    {
       result.add(new Address{
         location = source.HomeAddress,
         type = addressType.Home
       });
    }
    if(!String.IsNullOrEmpty(source.OfficeAddress))
    {
       result.add(new Address{
         location = source.OfficeAddress,
         type = addressType.Office
       });
    }
    return result;
  }
}

我面临的问题是,当我定义我这样写的探查器时,我似乎无法通过 personSrc class :

CreateMap<personSrc, personDest>()
    .ForMember(dest => dest.name, opt => opt.MapFrom(src => src.name))
    .ForMember(dest => dest.phone, opt => opt.MapFrom(src => src.phone))
    .ForMember(dest => dest.addresses, opt => opt.MapFrom<customResolver>(src => src) // this line is not working
    .ForMember(dest => dest.addresses, opt => opt.MapFrom<customResolver>() // this line is also not working

很可能我的配置文件没有正确实施,但我似乎找不到正确实施的示例。

您的个人资料是正确的。我试过你的例子,我已经设法将值映射到你的目的地class,你的个人资料应该是这样的:

public class CustomProfiler : Profile
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="CustomerProfile"/> class.
    /// </summary>
    public CustomProfiler()
    {
      CreateMap<personSrc, personDest>()
     .ForMember(dest => dest.name, opt => opt.MapFrom(src => src.name))
     .ForMember(dest => dest.phone, opt => opt.MapFrom(src => src.phone))
     .ForMember(dest => dest.addresses, opt => opt.MapFrom<CustomResolver>());
    }
  }

我已经用例子试过了:

var personSrc = new personSrc { HomeAddress = "HomeAddress", OfficeAddress = "OfficeAddress", name = "name", phone = "phone" };
      var personDest = mapper.Map<personDest>(personSrc);

你走在正确的轨道上。你能试试看是否适合你吗?