Come mappare un oggetto con un elenco nidificato all'elenco di oggetti utilizzando Automapper o LINQ?

Come mappare un oggetto con un elenco nidificato all'elenco di oggetti utilizzando Automapper o LINQ?

Soluzione per Come mappare un oggetto con un elenco nidificato all'elenco di oggetti utilizzando Automapper o LINQ?
è riportato di seguito:

Ho modelli come questo:

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class Exam
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }​

   ​ public class StudentExam
   ​ {
        ​public int Id { get; set; }
       ​ public int StudentId { get; set; }
       ​ public string ExamId{ get; set; }
   ​ }

StudentExam è una tabella di collegamento per i modelli Student ed Exam. Dall'applicazione frontend, raccolgo alcuni dati in questo modello:

   ​public class StudentExamModel
   ​{
       ​public int StudentId { get; set; }
       ​public List<Exam> Exams { get; set; }
   ​}

Quindi, in questo StudentExamModel ho ad esempio StudentId =3 con un elenco di 3 esami con ID 1, 2 e 3 (i nomi degli esami non sono importanti in questo momento). Posso mappare questo StudentExamModel su StudentExam usando Automapper, quindi ho 3 righe all'interno di StudentExam in questo modo:

    ​StudentId ExamId
   ​  3         1
   ​  3         2
   ​  3         3

?

Che ne dici di questo profilo?

public class MyMapping : Profile
{
    public MyMapping()
    {
        CreateMap<StudentExamModel, IReadOnlyList<StudentExam>>()
            .ConvertUsing(model => model.Exams
                                .Select(exam => new StudentExam { StudentId = exam.Id, ExamId = exam.Id.ToString() })
                                .ToList());
    }
}

Utilizzo:

var config = new MapperConfiguration(conf => conf.AddProfile<MyMapping>());
var mapper = config.CreateMapper();

var source = new StudentExamModel
{
    StudentId = 3,
    Exams = new List<Exam>
    {
        new Exam { Id = 1 },
        new Exam { Id = 2 },
        new Exam { Id = 3 },
    }
};

var dest = mapper.Map<IReadOnlyList<StudentExam>>(source);

foreach (var item in dest)
{
    Console.WriteLine($"{item.StudentId} - {item.ExamId}");
}

Ecco il violino corrispondente. E se avevi già fornito un tale violino in cui mancava solo la mappatura stessa, sarebbe stato molto più facile aiutarti. 😉