我已经阅读了这篇很棒的问答,并尝试制作类似的东西。我的模型类是:
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()
{
this.CoursesAttending = new List<Course>();
}
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public ICollection<Person> Students { get; set; }
}
public class PersonCourse
{
[Key, Column(Order = 0)]
public int PersonID { get; set; }
[Key, Column(Order = 1)]
public int CourseID { get; set; }
public virtual Person Student { get; set; }
public virtual Course StudentCourse { get; set; }
public int Mark { get; set; }
public string Comment { get; set; }
}
public class SchoolContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Person> People { get; set; }
public DbSet<PersonCourse> PersonCourseLinks { get; set; }
public SchoolContext()
: base("ManyToManyTest")
{
}
}
现在,我尝试添加一个新人并将新课程添加到他的课程列表中:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
Course studentCourse;
try
{
studentCourse = db.Courses.ToList<Course>().First();
}
catch
{
studentCourse = new Course() { Title = "HTML" };
}
person.CoursesAttending.Add(studentCourse);
db.People.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
一切顺利,但是当我打开创建的数据库时,我看到 Person 和 Course 类有 2 个链接表 - PersonCourse(带有字段:PersonID、CourseID、Mark、Comment)和 PersonCourse1(带有字段:PersonID、CourseID),并且只有 PersonCourse1 有行(实际上是一行)。为什么会这样?我做错了什么吗?我希望只看到一个链接表 - PersonCourses 表......