AutoMapper 在对象列表中映射嵌套的对象列表

AutoMapper map nested list of objects within list of objects

我有这些 类:

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

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

这些是我的 ViewModel:

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

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

这是我用来将 CoursesList 映射到 CourseVMList 的代码。我在尝试将 属性 Exams 映射到 CourseVM 时遇到问题,因为 ViewModel 也是 (ExamVM)。关于如何使用 AutoMapper 执行此操作的任何想法?

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

更新 映射规则:

CreateMap<Course, CourseVM>()

你写了MappingProfile吗?

如果你想使用自动映射器,你必须告诉他你想如何映射。

有自动映射器配置文件的示例:

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>();
        
        
        
        }

确保指定了正确的配置:

CreateMap<Exam, ExamVM>();

尝试从字段中创建属性:

public int CourseId { get; set; }