'IQueryable Result set not getting correct data

I have an object Student, which has a navigation property to Class:

public class Student
{
   public virtual List<Class> Classes {get; set;}
}

public class Class
{
   public byte? Code {get; set;}
}

I have a StudentVM which has the Code in it for the class.

public class StudentVM
{
       public virtual List<Class> Classes {get; set;}
       public byte>? Code {get; set;}
}

In my StudentVM, my Code is not getting assigned properly.

public IQueryable<StudentVM> GetStudents()
{
     IQueryable<StudentVM> query = dbSet
                    .AsNoTracking()
                    .Include(x => x.Classes);

     var students = query.Select(x => new StudentVM 
                    {
                        Classes = x.Classes
                    });

     foreach (var s in students)
     {
        if (s.Classes.Any())
        {
           s.Code = s.Classes.FirstOrDefault().Code;
        }
     }

     return students;
}

The goal here is to check if the list of classes has anything in it, and if so, get the Code property from the first one in the list and map it to the StudentVM.Code property. However, when I inspect the return student list ResultsView, the studentVM.Code is null when it should have data. I'm new to IQueryable and I'm not sure what I'm doing wrong here.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source