簡體   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