首页 > 解决方案 > EF Core 看到一对多和多对多 null

问题描述

我正在尝试播种数据,但我的映射似乎都没有工作。我相信我正在关注文档中的[教科书示例][1],但我一定遗漏了一些东西。

我的课程

    public class HighSchoolRegistrationModel
    {
        public long Id{ get; set; }
        [Required]
        public string SchoolName { get; set; }

        [Required]
        public string Address { get; set; }

        [Required]
        [EmailAddress]
        public string SchoolEmail { get; set; }
        public ICollection<CourseModel> CourseModelsOffered { get; set; }
        public ICollection<Student> Students { get; set; }

    }

    public class Student
    {
        public long StudentId { get; set; }
        public string Name { get; set; }
        public long HighSchoolRegistrationModelId { get; set; }
        public HighSchoolRegistrationModel HighSchoolRegistrationModel { get; set; }
        public Grade CurrentGradeLevel { get; set; }
        public ICollection<Guardian> Guardians { get; set; }
        public ICollection<Result> Results { get; set; }
        public ICollection<CourseInstance> Courses { get; set; }
        public ICollection<CourseGrade> CourseGrades { get; set; }
        public ICollection<ReportCard> ReportCards { get; set; }
    }

    public class Result
    {
        public long ResultId{ get; set; }
        public long StudentId { get; set; }
        public Student Student { get; set; }
        public Exam ExamType { get; set; }
        public double Score { get; set; }
    }

我的上下文类

        // HighSchoolContext, my only context
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<HighSchoolRegistrationModel>().HasData(
                new HighSchoolRegistrationModel 
                { 
                    Id = 1, 
                    SchoolName = "Nouveau Blaise Pascal", 
                    Address = "123 Rue du Ciel",
                    SchoolEmail = "npb@fauxemails.fr"
                }
            );
            modelBuilder.Entity<CourseModel>().HasData(
                new CourseModel()
                {
                    Id = 1,
                    CourseName = "Maths",
                    GradeLevel = Grade.Fifth,
                    HighSchoolRegistrationModelId = 1
                },
                new CourseModel()
                {
                    Id = 2,
                    CourseName = "Language",
                    GradeLevel = Grade.Fifth,
                    HighSchoolRegistrationModelId = 1
                }
            );
            modelBuilder.Entity<Student>().HasData(
                new Student() 
                { 
                    StudentId = 1, 
                    Name = "Camille Foussoulou",
                    CurrentGradeLevel = Grade.Fifth,
                    HighSchoolRegistrationModelId = 1
                },
                new Student()
                {
                    StudentId = 2,
                    Name = "Lucas Foussoulou",
                    CurrentGradeLevel = Grade.Fifth,
                    HighSchoolRegistrationModelId = 1
                }
            );
            modelBuilder.Entity<Guardian>().HasData(
                new Guardian()
                {
                    GuardianId = 1,
                    Name = "Joseph Foussoulou"
                },
                new Guardian()
                {
                    GuardianId = 2,
                    Name = "Jeanne Ntoume"
                }
            );
            modelBuilder.Entity<GuardianStudent>().HasData(
                new GuardianStudent() { GuardianId = 1, StudentId = 1},
                new GuardianStudent() { GuardianId = 1, StudentId = 2},
                new GuardianStudent() { GuardianId = 2, StudentId = 1},
                new GuardianStudent() { GuardianId = 2, StudentId = 2}
            );
            modelBuilder.Entity<Result>().HasData(
                new Result()
                {
                    ResultId = 1,
                    StudentId = 1,
                    ExamType = Exam.Art,
                    Score = 77.7
                },
                new Result()
                {
                    ResultId = 2,
                    StudentId = 1,
                    ExamType = Exam.Language,
                    Score = 77.5
                }
            ...//more results
            );
            modelBuilder.Entity<Instructor>().HasData(
                new Instructor() { InstructorId = 1, Name = "Jacques Alassane" },
                new Instructor() { InstructorId = 2, Name = "Alice des Plaines" }
            );
            modelBuilder.Entity<CourseInstance>().HasData(
                new CourseInstance()
                {
                    CourseInstanceId = 1,
                    CourseModelId = 1,
                    InstructorId = 1,
                },
                new CourseInstance()
                {
                    CourseInstanceId = 2,
                    CourseModelId = 2,
                    InstructorId = 2,
                }
            );
            modelBuilder.Entity<CourseGrade>().HasData(
                new CourseGrade()
                {
                    CourseGradeId = 1,
                    StudentId = 1,
                    CourseInstanceId = 1,
                    Grade = 75.3
                },
                new CourseGrade()
                {
                    CourseGradeId = 2,
                    StudentId = 1,
                    CourseInstanceId = 1,
                    Grade = 72.3
                }
                //more grades
            );
            modelBuilder.Entity<CourseInstanceStudent>().HasData(
                new CourseInstanceStudent() { CourseInstanceId = 1, StudentId = 1},
                new CourseInstanceStudent() { CourseInstanceId = 1, StudentId = 2},
                new CourseInstanceStudent() { CourseInstanceId = 2, StudentId = 1},
                new CourseInstanceStudent() { CourseInstanceId = 2, StudentId = 2}
            );
        }

然而,当运行添加迁移、更新数据库、启动我的应用程序并点击api/Students(邮递员中的标准 http get)时,我Student的 s 没有任何Results。也没有我打算为此播种的集合中的任何其他实体。我错过了什么?

编辑

为了澄清更多,我的api:

// StudentsController.cs
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
        {
            return await _context.Students.ToListAsync();
        }

我在前端调用它的地方

//StudentService.cs

        public async Task<IEnumerable<Student>> GetStudentsAsync()
        {
            var options = new JsonSerializerOptions()
            {
                ReferenceHandler = ReferenceHandler.Preserve,
                PropertyNameCaseInsensitive = true
            };
            return await http.GetFromJsonAsync<IEnumerable<Student>>("api/Students", options);
        }

响应:

{"$id":"1","$values":[{"$id":"2","studentId":1,"name":"Camille Foussoulou","highSchoolRegistrationModelId":1,"highSchoolRegistrationModel":null,"currentGradeLevel":1,"guardians":null,"results":null,"courses":null,"courseGrades":null,"reportCards":null},{"$id":"3","studentId":2,"name":"Lucas Foussoulou","highSchoolRegistrationModelId":1,"highSchoolRegistrationModel":null,"currentGradeLevel":1,"guardians":null,"results":null,"courses":null,"courseGrades":null,"reportCards":null}]}

我运行的命令

dotnet ef migrations add InitialCreate -c HighSchoolContext
dotnet ef database update -c HighSchoolContext

目前使用 Sqlite。[1]:https ://docs.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

标签: c#asp.net-coreentity-framework-core

解决方案


事实证明,我只是忘记定义要包含在我从数据库中读取的实体中的相关数据。在这个例子中,为了得到我刚刚这样做的ResultsStudent

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Student>>> GetStudents()
        {
            return await _context.Students
                    .Include(s => s.Results)
                    .ToListAsync();
        }

这是急切的加载,随着我的继续,我可能会探索不同的加载策略。


推荐阅读