Mapping one source class to multiple derived classes with automapper

后端 未结 3 1383
忘掉有多难
忘掉有多难 2021-02-03 22:46

Suppose i have a source class:

public class Source
{
    //Several properties that can be mapped to DerivedBase and its subclasses
}

And some d

3条回答
  •  深忆病人
    2021-02-03 23:28

    For Automapper 8.0.
    Current version has new method IncludeAllDerived
    Here's working example:

            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap()
                    .ForMember(dest => dest.Test3, opt => opt.MapFrom(src => src.Test))
                    .IncludeAllDerived();
    
                cfg.CreateMap()
                    .ForMember(dest => dest.Test4, opt => opt.MapFrom(src => src.Test2));
    
                cfg.CreateMap()
                      .ForMember(dest => dest.Test5, opt => opt.MapFrom(src => src.Test2));
            });
    
            var mapper = config.CreateMapper();
    
            var source = new Source { Test = "SourceTestProperty", Test2 = "SourceTest2Property" };
            var d1 = mapper.Map(source);
            var d2 = mapper.Map(source);
    
            Assert.Equal("SourceTestProperty", d1.Test3);
            Assert.Equal("SourceTest2Property", d1.Test4);
    
            Assert.Equal("SourceTestProperty", d2.Test3);
            Assert.Equal("SourceTest2Property", d2.Test5);
    

提交回复
热议问题