我正在尝试在 EF 中进行测试,创建多对多关系,因为我总是映射一对一或一对多,我在互联网上有一个示例可供尝试,该示例适用于插入寄存器,但我无法读取寄存器
这是我的课程,我不知道是什么HashSet
,我在网站上得到了这个代码
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Course> CoursesAttending { get; set; }
public Person()
{
CoursesAttending = new HashSet<Course>();
}
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public ICollection<Person> Students { get; set; }
public Course()
{
Students = new HashSet<Person>();
}
}
这是我的上下文
public class SchoolContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Person> People { get; set; }
public SchoolContext()
: base("MyDb")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().
HasMany(c => c.Students).
WithMany(p => p.CoursesAttending).
Map(
m =>
{
m.MapLeftKey("CourseId");
m.MapRightKey("PersonId");
m.ToTable("PersonCourses");
});
}
}
当我插入寄存器是正确的
static void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Course math = new Course();
Course history = new Course();
Course biology = new Course();
math.Title = "Math";
history.Title = "History";
biology.Title = "Biology";
db.Courses.Add(math);
db.Courses.Add(history);
db.Courses.Add(biology);
Person john = new Person();
john.FirstName = "John";
john.LastName = "Paul";
john.CoursesAttending.Add(history);
john.CoursesAttending.Add(biology);
db.People.Add(john);
db.SaveChanges();
}
}
但是当我尝试为显示内容选择注册时,它不起作用,它什么也不打印
static void Main(string[] args)
{
using (SchoolContext db = new SchoolContext())
{
Pearson p = db.Peasons.First();
Console.WriteLine(p.CoursesAttending.First().Title);
}
}
我在数据库中检查过,寄存器存在,是什么问题?
请先教我如何在与代码的多对多关系中进行选择。