我正在建立一个电子学习系统,用户可以在其中注册一个课程.课程可以由一系列内容组成,也可以由一系列包含内容的课程部分组成。
我的模型定义如下:
public class Course
{
[Key]
public int CourseID { get; set; }
//1 to many relationship
public virtual ICollection<Content> Contents { get; set; }
public virtual ICollection<CourseSection> CourseSections { get; set; }
//many to many relationship
public virtual ICollection<User> Users { get; set; }
}
public class CourseSection
{
[Key]
public int CourseSectionID { get; set; }
public int CourseID { get; set; }
public virtual ICollection<Content> Contents { get; set; }
}
public class Content
{
[Key]
public int ContentID { get; set; }
//many-to-many mappings
public virtual ICollection<Course> Courses { get; set; }
public virtual ICollection<CourseSection> CourseSections { get; set; }
}初始化上下文之后,我可以看到数据库中创建了两个与我创建的模型无关的表。意外地创建了以下两个表,我想了解其中的原因:
ContentCourse: Content_ContentID,Course_CourseID
CourseSectionContent: CourseSection_CourseSectionID,Content_ContentID
注意到正在创建这两个表之后,我决定通过添加以下两个模型为、CourseContent、和创建映射表:
public class CourseContent
{
[Key, Column(Order = 0)]
public int CourseID { get; set; }
[Key, Column(Order = 1)]
public int ContentID { get; set; }
}
public class SectionContent
{
[Key, Column(Order = 0)]
public int CourseSectionID { get; set; }
[Key, Column(Order = 1)]
public int ContentID { get; set; }
}不幸的是,这些表仍在创建中。有人能从我的代码中看出我哪里出错了吗?任何帮助都将不胜感激。
发布于 2013-07-10 12:16:18
你说“1 to多关系”(Course.Contents),但事实并非如此。Course和Content有着多到多的关系。
因此,这些表不是意外创建的。创建它们是因为在关系数据库中建模多到多关联的唯一方法是创建连接表。您会注意到,当您将现有的Content项添加到Course.Contents中时,EF将在ContentCourse中插入记录,而不是在Course或Content中插入记录。
您自己定义的类与类模型中的任何其他类无关。因此,EF将不会为它们创建表,如果创建了表,它们将只是断开连接的表。
如果您决定将连接表合并到概念模型(= class模型)中,则必须对模型进行相当大的更改。例如,对于CourseContent
public class CourseContent
{
[Key, Column(Order = 0)]
public int CourseID { get; set; }
[ForeignKey("CourseID")]
public virtual Course Course { get; set; }
[Key, Column(Order = 1)]
public int ContentID { get; set; }
[ForeignKey("ContentID ")]
public virtual Content Content { get; set; }
}
public class Course
{
[Key]
public int CourseID { get; set; }
//1 to many relationship (now it is)
public virtual ICollection<CourseContent> Contents { get; set; }
...
}
public class Content
{
[Key]
public int ContentID { get; set; }
//many-to-many mappings
public virtual ICollection<CourseContent> Courses { get; set; }
...
}如果您想要保持多个关联,但也想控制连接表的名称,您可以使用像this answer中那样的流畅映射。
https://stackoverflow.com/questions/17569424
复制相似问题