0

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?

2
  • I just wondering so I asked.Lets say u fill formationModel with the CourseModel and QuestionModel and its values.How u planing to read those model values.As FormationModel only has LearningElementModel which is only contain Id fieald Commented Aug 6, 2015 at 10:50
  • 1
    With a JsonConverter where I can get a TypeName property and creates the good object! Commented Aug 6, 2015 at 11:03

1 Answer 1

1

We can use Include function from AutoMapper

AutoMapper.CreateMap<LearningElementModel, LearningElement>()
    .Include<CourseModel, Course>()
    .Include<MultipleChoiceQuestionModel, MultipleChoiceQuestion>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.