Home > other >  Mapping problem, object reference not set to an instance
Mapping problem, object reference not set to an instance

Time:12-19

I got a small problem here. I got a course class and a User. I want to show all the Users inside a Course through the API.

the error i get,

'Object reference not set to an instance of an object.'

And this is my controller method,

        var objList = _courseRepo.GetUsers(CourseId);
       
        if (objList == null)
        {
            return NotFound();
        }

        var objToShow = new List<ViewCourseDetailsDTO>();

        foreach (var obj in objList)
        {

            objToShow.Add(_mapper.Map<ViewCourseDetailsDTO>(obj));
            
        }



        
        return Ok(objToShow);

The Error i got is inside the Foreach-loop. It says that i need to create an object...

This is how my DTO classes looks like,

 public class ViewCourseDetailsDTO
    {
        public int CourseId { get; set; }
        public string CourseTitle { get; set; };
        public ICollection<UserDTO>? Users { get; set; } = new List<UserDTO>();
    }

And this one,

  public class UserDTO
    {
        public string ID { get; set; }
        public string UserName { get; set; }
        public string Name { get; set; }

    }

Do you think i have to break out the UserDTO somehow? Is it Therefore u think ?

if you want to see my CourseRepository than its here,

 public ICollection<Course> GetUsers(int courseId)
        {
            return _db.Course.Where(c => c.CourseId == courseId).Include(a => a.Users).ToList();
        }

Would be really grateful if you could help me out here.

CodePudding user response:

Wohooo I found it, damnit! On my controller, i forgot to put in mapper here,

 public CourseController(ICourseRepository courseRepo, IMapper mapper)
        {
            _courseRepo = courseRepo;
            _mapper = mapper;
        }

I had injected it correct at the top but forgot to put it inside there ^

  • Related