0

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>()
4
  • Are mapper rules specified? Commented May 12, 2021 at 15:37
  • @feihoa yes, added then in the question too, trying different things in that direction now Commented May 12, 2021 at 15:39
  • CreateMap<Exam, ExamVM>() is specified as well? Also, try to make all the fields properties: public int CourseId {get; set;} Commented May 12, 2021 at 15:41
  • @feihoa tried that and worked, just came back to put an answer and saw your comment, feel free to add it as an answer and I'll choose it ;) Commented May 12, 2021 at 15:46

2 Answers 2

1

Be sure that proper config is specified:

CreateMap<Exam, ExamVM>();

Try to make properties from the fields:

public int CourseId { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.