我已阅读this great Q&A,我试图做出类似的东西。我的模型类:EF-code-first多对多相关对象生成两个不同的SQL表(MVC3)
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类有PersonCourse(包括PersonID,CourseID,Mark,Comment)和PersonCourse1(包含字段PersonID,CourseID),并且只有PersonCourse1有行(实际上是一行)。为什么会发生?我做了一些不正确的事吗?我希望看到只有一个链接表 - 在PersonCourses表...
根据您使用的EF版本,它会为您创建多个桥表(PersonCourse)。还值得注意的是,您不需要初始化集合以在您的构造函数中列出,因为DbContext应该为您处理。你有没有看到[本文](http://weblogs.asp.net/scottgu/archive/2010/07/23/entity-framework-4-code-first-custom-database-schema-mapping.aspx)? – Basic