Reputation: 947
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?
Upvotes: 0
Views: 1397
Reputation: 947
We can use Include function from AutoMapper
AutoMapper.CreateMap<LearningElementModel, LearningElement>()
.Include<CourseModel, Course>()
.Include<MultipleChoiceQuestionModel, MultipleChoiceQuestion>();
Upvotes: 1