我是实体框架的新手,我在正确定义关系方面遇到了问题。
我有一个Student
类和一个Course
类它们应该是多对多关系。一个学生可以学习一门或多门课程,一门课程可以由一个或多个学生完成。但是,当我尝试运行命令dotnet ef migrations add InitialCreate
来创建初始迁移时,我得到了错误:The entity type 'List<int>' requires a primary key to be defined
。这是Student
类
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
namespace Advisment.Models
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int MajorId { get; set; }
public int AdvisorId { get; set; }
public List <int> CompletedCourses { get; set; }//List of courses done by student
public ICollection <Course> Courses { get; set; }//Reference the Course class
public Advisor Advisor { get; set; }
public Major Major { get; set; }
}
}
这里是Course
类:
using System;
using System.ComponentModel.DataAnnotations;
namespace Advisment.Models
{
public class Course
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
public int MajorId { get; set; }
public ICollection <Student> Students { get; set; }//Store student objects
public Major Major { get; set; }
}
}
根据我的理解,ICollection(s)是用来引用类的,但我不确定我是否正确使用它。
你应该添加第三个类,它应该是学生和课程之间的桥梁。因为学生和课程之间的关系是多对多的。
考虑这个类:
public class Enrollment
{
public int CourseId { get; set; }
public int StudentId { get; set; }
public Student Student { get; set; }
public Course { get; set; }
public char Grade {get; set; }
}
把你的student class改成如下
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int MajorId { get; set; }
public int AdvisorId { get; set; }
public ICollection <Enrollment> Enrollments { get; set; }//Reference the Enrollment class
public Advisor Advisor { get; set; }
public Major Major { get; set; }
}
和Course
类像这样:
public class Course
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
public int MajorId { get; set; }
public ICollection <Enrollment> Enrollments{ get; set; }//Store student objects
public Major Major { get; set; }
}
在Fluent Api中,您需要像这样设置桥注册表的关系:
modelBuilder.Entity<Enrollment>()
.HasKey(c => new { c.CourseId, c.StudentId});
modelBuilder.Entity<Enrollment>()
.HasOne(c => c.Student)
.WithMany(s => s.Enrollments)
.HasForeignKey(h => h.StudentId)
.IsRequired();
modelBuilder.Entity<Enrollment>()
.HasOne(c => c.Course)
.WithMany(j => j.Courses)
.HasForeignKey(h => h.CourseId)
.IsRequired();
要检索学生修过的所有课程,您可以使用以下方法
context.Students.Include(s => s.Enrollments).ThenInclude(e => e.Course).ToList();
Hello为了创建表之间的关系,您需要添加一个外键,这是您尝试连接的表中的主键。
所以你需要找到你想要获取外键的表/类你在课程列表中做过,并实现了多对多吗的关系。现在只需将外键添加到student类
例如:
public int CourseId { get; set; }
为学生添加主键[Key]
。