繁体   English   中英

(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());

然后,我映射到一个队形对象:

var formation = new Formation();
Automapper.Mapper.Map(formationModel, formation);

问题在于编排具有包含学习元素的列表,而不具有包含Question元素和Course元素的列表。

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

如何更正此映射?

我们可以使用AutoMapper中的Include函数

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM