N
N
Natalia Star2019-11-22 14:34:11
C++ / C#
Natalia Star, 2019-11-22 14:34:11

How to get a collection of students of a certain grade?

Model code:

public class Grade
    {
        public Grade()
        {
            Students = new HashSet<Student>();
        }
        [Key]
        public int GradeId { get; set; }
        public string GradeName { get; set; }
        public string Section { get; set; }

        public ICollection<Student> Students { get; set; }
    }
public class Student
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }

        public int CurrentGradeId { get; set; }
        public Grade Grade { get; set; }
    }

Database context description code:
public DbSet<Grade2> Grades2 { get; set; }
        public DbSet<Student> Students { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
modelBuilder.Entity<Student>()
            .HasOne(s => s.Grade)
             .WithMany(g => g.Students)
            .HasForeignKey(s => s.CurrentGradeId);
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2019-11-22
@euforia72

The way you wrote the model means to the EntityFramework that it must use explicit loading for the Students collection. You need to do something like:

var gradesWithStudents = await _context.Grades.Include(o => o.Students).ToArrayAsync();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question