简体   繁体   中英

AutoMapper map nested list of objects within list of objects

I have these classes:

public class Course
{
public int CourseId;
public List<Exam> Exams;
}

public class Exam
{
public int ExamId;
public float Score;
}

These are my ViewModels:

public class CourseVM
{
public int CourseId;
public List<ExamVM> Exams;
}

public class ExamVM
{
public int ExamId;
public float Score;
public bool Selected;
}

This is the code I'm using to map a List of Courses to a List of CourseVM . I'm having a problem trying to map the property Exams within CourseVM since is a ViewModel too( ExamVM ). Any idea on how to do this using AutoMapper ?

examsVM = _mapper.Map<List<Course>, List<CourseVM>>(coursesList);

UPDATE Mapping rules:

CreateMap<Course, CourseVM>()

Did you write MappingProfile?

If u want to use automapper u have to tell him how u wanna map.

there is example of automapper profile:

 public class RestaurantMappingProfile: Profile { public RestaurantMappingProfile() { CreateMap<Restaurant, RestaurantDto>().ForMember(m => m.City, c => c.MapFrom(s => s.Address.City)).ForMember(m => m.Street, c => c.MapFrom(s => s.Address.Street)).ForMember(m => m.ZipCode, c => c.MapFrom(s => s.Address.ZipCode)); CreateMap<Dish, DishDto>(); CreateMap<CreateRestaurantDto, Restaurant>().ForMember(r => r.Address, c => c.MapFrom(dto => new Address() { City = dto.City, ZipCode = dto.ZipCode, Street = dto.Street })); CreateMap<CreateDishDto, Dish>(); }

Be sure that proper config is specified:

CreateMap<Exam, ExamVM>();

Try to make properties from the fields:

public int CourseId { get; set; }

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