自动映射 - 创建自定义属性映射,其中源对象不知道且属性名称不匹配?

时间:2017-04-26 23:31:21

标签: c# asp.net .net automapper

这个头衔令人困惑。用代码展示会更容易一些。以下是背景类:

public interface ISearch { }

public class Search1 : ISearch
{
    public string PROP1 { get; set; }
}

public class Search2 : ISearch
{
    public string PROP2 { get; set; }
}

public class SearchFinal
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

这就是我想要做的事情:

public class SomeClass
{
    IMapper mapper;

    public SomeClass()
    {
        //This config fails validation
        var config = new MapperConfiguration(cfg => {
            cfg.CreateMap<ISearch, SearchFinal>()
                .ForMember(dest => dest.Prop1, opts => opts.MapFrom("PROP1"))
                .ForMember(dest => dest.Prop2, opts => opts.MapFrom("PROP2"));
        });
        mapper = new Mapper(config);
    }

    public void SearchMethod(ISearch search)
    {
        SearchFinal test = mapper.Map<SearchFinal>(search);

        // Do query stuff
    }
}

配置在运行时失败,因为&#34; PROP1&#34; /&#34; PROP2&#34;属性不存在于界面中。有没有办法设置这个地图?围绕这个问题的任何其他方法,没有重组这个令人难以置信的丑陋的代码结构?

1 个答案:

答案 0 :(得分:1)

只需为每个接口实现创建映射(因此您也将仅对每个类中存在的属性使用映射 - 即不尝试为Prop2类映射Search1

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<Search1, SearchFinal>()
        .ForMember(dest => dest.Prop1, opts => opts.MapFrom(src => src.PROP1));

    cfg.CreateMap<Search2, SearchFinal>()
        .ForMember(dest => dest.Prop2, opts => opts.MapFrom(src => src.PROP2));
});

接下来传递ISearch接口的一些实现,该接口映射到SearchFinal

ISearch search = new Search1 { PROP1 = "foo" };
// note that you are mapping variable of ISearch type here
SearchFinal test = mapper.Map<SearchFinal>(search);

输出:

{
  "Prop1": "foo",
  "Prop2": null
}