Automapper 4.2.1 - 抽象基类的平面模型(TPT结构)

时间:2016-05-04 18:41:38

标签: c# asp.net-web-api automapper automapper-4

我无法从Flat模型映射到抽象基类(TPT结构)。 使用版本4.2.1 来源模型:

 public class FlatModel
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public ModelType Type {get; set}

        public string TestA { get; set; }

        public string TestB { get; set; }

    }

目的地模特:

 public abstract class BaseModel
    {
            public int Id { get; set; }
            public string Description { get; set; }

    }

public class ModelA : BaseModel
{
       public string TestA { get; set; }

}

public class ModelB : BaseModel
{
       public string TestB { get; set; }

}

我试过的映射

由于抽象类的原因,这个映射会出错!

public static IConfigurationProvider CreateConfig()
        {
            var config = new MapperConfiguration(
                t =>
                {
                              t.CreateMap<FlatModel, BaseModel>()
                                .Include<FlatModel, ModelA>()
                                  .Include<FlatModel, ModelB>()
                               .ReverseMap();

                         t.CreateMap<FlatModel, ModelA>()
                               .ReverseMap();  

                         t.CreateMap<FlatModel, ModelB>()
                               .ReverseMap();   
                }


       }

另一个尝试 - 这个更接近,但目标(ModelA,ModelB,BaseModel)始终为null

 public static IConfigurationProvider CreateConfig()
        {
            var config = new MapperConfiguration(
                t =>
                {


                t.CreateMap<FlatModel, BaseModel>()
                    .ConvertUsing<CustomTypeConverter>();

                //The Reverse
                t.CreateMap<BaseModel, FlatModel>()
                        .Include<ModelA, FlatModel>()
                         .Include<ModelB, FlatModel>();

                }
        }



    public class CustomTypeConverter : ITypeConverter<FlatModel, BaseModel>
    {

        public BaseModel Convert(ResolutionContext context)
        {
            var src = (FlatModel)context.SourceValue;

            if (src.Type == "ModelA")
            {
                return new ModelA();
            }
            else if (src.Type == "ModelB")
            {
                return new ModelB();
            }
            return null;
        }

    }

呼叫映射

  (config as MapperConfiguration).CreateMapper().Map<BaseModel>(source);

0 个答案:

没有答案