问题
I have configuration file in JSON format that have a list of configurations for my classes. I read configuration to BaseDTO class that have all common configurations and I would like to map those BaseDTO to specific implementations of Base class basing on field Type. Is there any way to tell automapper to use some custom mapping logic to tell it which class to create?
//Map in automapper: CreateMap<BaseDTO, Base>();
public class BaseDTO
{
public string Type { get; set; }
// rest of config from json
}
public class Base
{
public string Type { get; set; }
// rest of config mapped from BaseDTO
}
public class A : Base
{
}
public class B : Base
{
}
public class C : Base
{
}
回答1:
You can use ConstructUsing method to define which object to create based on Type property of BaseDTO class and then in BeforeMap map source BaseDTO instance to created destination object. I allowed me to change you classes a little bit for example
public class BaseDTO
{
public string Type { get; set; }
public string AValue { get; set; }
public string BValue { get; set; }
public string CValue { get; set; }
}
public class Base
{
public string Type { get; set; }
}
public class A : Base
{
public string AValue { get; set; }
}
public class B : Base
{
public string BValue { get; set; }
}
public class C : Base
{
public string CValue { get; set; }
}
And I used following automapper configuration
var configuration = new MapperConfiguration(
conf =>
{
conf.CreateMap<BaseDTO, Base>()
.ConstructUsing(s => Create(s.Type))
.BeforeMap((s, d, c) => c.Mapper.Map(s, d));
conf.CreateMap<BaseDTO, A>();
conf.CreateMap<BaseDTO, B>();
conf.CreateMap<BaseDTO, C>();
});
Body of Create method is (you can create a separate factory class or it)
private static Base Create(string type)
{
switch (type)
{
case "A":
return new A();
case "B":
return new B();
case "C":
return new C();
default:
throw new Exception("Unknown type");
}
}
And following example shows how it works (first object is mapped to A class, second to B, ...)
var mapper = configuration.CreateMapper();
var dtos = new[]
{
new BaseDTO {Type = "A", AValue = "a-value"},
new BaseDTO {Type = "B", BValue = "b-value"},
new BaseDTO {Type = "C", CValue = "c-value"}
};
var result = mapper.Map<Base[]>(dtos);
来源:https://stackoverflow.com/questions/49208788/how-to-map-to-class-with-multiple-implementations-using-automapper