(AutoMapper)如何映射一个有不同对象列表的对象
本文关键字:对象 一个 列表 AutoMapper 何映射 映射 | 更新日期: 2023-09-27 18:06:33
我有一个LearningElement:
public class LearningElement
{
public int Id { get; set; }
}
和一些学习元素:
public class Course : LearningElement
{
public string Content { get; set; }
}
public class Question: LearningElement
{
public string Statement { get; set; }
}
现在我有一个可以包含许多学习元素的形成:
public class Formation
{
public ICollection<LearningElement> Elements { get; set; }
}
最后我的视图模型:
public class LearningElementModel
{
public int Id { get; set; }
}
public class CourseModel : LearningElementModel
{
public string Content { get; set; }
}
public class QuestionModel: LearningElementModel
{
public string Statement { get; set; }
}
public class FormationModel
{
public ICollection<LearningElementModel> Elements { get; set; }
}
所以我创建了地图:
AutoMapper.CreateMap<LearningElement, LearningElementModel>().ReverseMap();
AutoMapper.CreateMap<Course, CourseModel>().ReverseMap();
AutoMapper.CreateMap<Question, QuestionModel>().ReverseMap();
AutoMapper.CreateMap<Formation, FormationModel>().ReverseMap();
现在,假设我有这个视图模型
var formationModel = new FormationModel();
formationModel.Elements.Add(new CourseModel());
formationModel.Elements.Add(new QuestionModel());
然后映射到一个Formation对象:
var formation = new Formation();
Automapper.Mapper.Map(formationModel, formation);
问题是,formation有一个包含学习元素的列表,而不是一个包含Question元素和Course元素的列表。
AutoMapper忽略了formationModel.Elements
中的元素不完全是LearningElementModel
,而是QuestionModel
和CourseModel
。
我如何纠正这个映射?
我们可以使用AutoMapper的Include函数
AutoMapper.CreateMap<LearningElementModel, LearningElement>()
.Include<CourseModel, Course>()
.Include<MultipleChoiceQuestionModel, MultipleChoiceQuestion>();