(AutoMapper)如何映射具有不同对象列表的对象?

(AutoMapper) How to map an object which has a list of different objects?

我有一个 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 有一个包含学习元素的列表,而不是一个包含问题元素和课程元素的列表。

AutoMapper 忽略 formationModel.Elements 中的元素不完全是 LearningElementModel,而是 QuestionModelCourseModel

如何更正此映射?

我们可以使用 AutoMapper 的 Include 函数

AutoMapper.CreateMap<LearningElementModel, LearningElement>()
    .Include<CourseModel, Course>()
    .Include<MultipleChoiceQuestionModel, MultipleChoiceQuestion>();