我有一个模型,该模型的属性需要映射到抽象类ClassAModel和ClassBModel与ClassA和ClassB一对一的实体
public class Model
{
public int Number { get; set; }
public ClassAModel ClassAModel { get; set; }
public ClassBModel ClassBModel { get; set; }
}
public abstract class AbstractClass
{
public int Number { get; set; }
}
public class ClassA : AbstractClass
{
}
public class ClassB : AbstractClass {
}
我不知道如何告诉自动映射器从ClassAModel属性映射ClassA
答案 0 :(得分:-1)
此答案假设您尝试使用Model
中的属性和ClassA
中的number属性将ClassAModel
映射到Model
:
CreateMap<Model, ClassA>()
.ConstructProjectionUsing(x => new ClassA(){Name = x.ModelClassA.Name, Number = x.Number});
此答案假定您要将Model
映射到ClassA
和ClassB
的实例。这使用了动态包装两个对象。
CreateMap<Model, dynamic>()
.ConstructProjectionUsing(x => new { A = new ClassA() { Name = x.ModelClassA.Name, Number = x.Number },
B = new ClassB() { Department = x.ModelClassA.Name, Number = x.Number }});
希望这些对您有所帮助。
要减少手动映射,您可以改为执行以下操作(未经测试的代码):
CreateMap<Model, ClassA>()
.ConstructProjectionUsing(x => Mapper.Map<ClassA>(x.ModelClassA))
.ForMember(x => x.Number, y => y.MapFrom(src => src.Number));
CreateMap<Model, ClassB>()
.ConstructProjectionUsing(x => Mapper.Map<ClassB>(x.ClassBModel))
.ForMember(x => x.Number, y => y.MapFrom(src => src.Number));
CreateMap<Model, dynamic>().ConstructProjectionUsing(x => new {A = Mapper.Map<Model, ClassA>(x), B = Mapper.Map<Model, ClassB>(x)});