1

我在从平面模型映射到抽象基类(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();   
                }


       }

另一个尝试——这个更接近了,但 Destination(ModelA, ModelB, BaseModel) 始终为空

 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);
4

0 回答 0