简体   繁体   中英

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

I have a LearningElement:

public class LearningElement
{
  public int Id { get; set; }
}

And some kinds of learning elements:

public class Course : LearningElement
{
  public string Content { get; set; }
}

public class Question: LearningElement
{
  public string Statement { get; set; }
}

Now I have a formation that can have many learning elements:

public class Formation 
{
  public ICollection<LearningElement> Elements { get; set; }
}

And finally my view models:

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; }
}

So I do create maps:

AutoMapper.CreateMap<LearningElement, LearningElementModel>().ReverseMap();
AutoMapper.CreateMap<Course, CourseModel>().ReverseMap();
AutoMapper.CreateMap<Question, QuestionModel>().ReverseMap();
AutoMapper.CreateMap<Formation, FormationModel>().ReverseMap();

Now, suppose I have this view model

var formationModel = new FormationModel();
formationModel.Elements.Add(new CourseModel());
formationModel.Elements.Add(new QuestionModel());

And I do the mapping to a Formation object:

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

The problem is that formation has a list with learning elements, and not a list with a Question element and a Course element.

AutoMapper ignores that the elements in formationModel.Elements are not exactly a LearningElementModel , but a QuestionModel and CourseModel .

How can I correct this mapping?

We can use Include function from AutoMapper

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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