I am having trouble mapping from a Flat model to a abstract base class (TPT structure). using version 4.2.1 Source Model:
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; }
}
Destination Models:
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; }
}
Mappings I have Tried
This one would error when mapping because of the abstract class!
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();
}
}
Another Try -- This one got closer, but the Destination(ModelA, ModelB, BaseModel) was always 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;
}
}
Call Mapping
(config as MapperConfiguration).CreateMapper().Map<BaseModel>(source);