6

I would like to map between two classes by using the following statements:

var directoryDataModel = new DirectoryDM()
{
    Title = "School Directory",
    Persons = new List<PersonDM>()
    {
        new TeacherDM() { Name = "Johnson", Department = "Math" },
        new StudentDM() { Name = "Billy", Classes = new List<string>() { "Math", "Physics" } }
    }                
};
var directoryViewModel = directoryDataModel.Adapt<DirectoryVM>();
var directoryDataModel2 = directoryViewModel.Adapt<DirectoryDM>();

What do I need to do so that it handles the mapping of the derived classes in the Persons list?

TeacherVM <=> TeacherDM and StudentVM <=> StudentDM

Data Model:

public class DirectoryDM
{
    public string Title;
    public List<PersonDM> Persons;
}
public class PersonDM
{
    public string Name;
}
public class TeacherDM : PersonDM
{
    public string Department;
}
public class StudentDM : PersonDM
{
    public List<string> Classes;
}

View Model:

public class DirectoryVM
{
    public string Title;
    public List<PersonVM> Persons;
    public bool AdditionalStuff;
}
public class PersonVM
{
    public string Name;
    public bool AdditionalStuff;
}
public class TeacherVM : PersonVM
{
    public string Department;
    public bool AdditionalStuff2;
}
public class StudentVM : PersonVM
{
    public List<string> Classes;
    public bool AdditionalStuff2;
}
Brian Rice
  • 3,107
  • 1
  • 35
  • 53

1 Answers1

6

I'm not sure if this has to be done everytime... or just once... but here is how to organice the "configs" for this model.

            TypeAdapterConfig<PersonDM, PersonVM>.NewConfig()
                .Include<TeacherDM, TeacherVM>()
                .Include<StudentDM, StudenVM>();

            var viewModel = dataModel.Adapt<FlexSortVM>();

and

            TypeAdapterConfig<PersonVM, PersonDM>.NewConfig()
                .Include<TeacherVM, TeacherDM>()
                .Include<StudentVM, StudenDM>();

            var dataModel = viewModel.Adapt<FlexSortDM>();
Brian Rice
  • 3,107
  • 1
  • 35
  • 53