EF代码中的多对多关系表示

时间:2011-12-23 06:55:04

标签: c# entity-framework many-to-many ef-code-first poco

我正在尝试以下列方式开发结构......

  • 我代表的是由教师授课的课程。
  • 对于每个课程都有任意数量的考试(因为考试是随机生成的,每一代都算作不同的考试),我必须在数据库中跟踪。
  • 0名或更多学生可以参加考试。 (相反,学生可以参加一项或多项考试。)
  • 一旦学生参加考试(通过我已经开发的网络界面完成),该学生将获得考试分数和考试分数(通过,失败,重新考试,TestOut等)
  • 还有一些其他的东西"在那里,我没有解决,例如考试是由问题(由教师创建)等组成,但我对此有很好的理解。

我几乎已经完成了我的结构,但我正在努力学习如何代表学生与考试的关系以及如何处理ExamStatus。到目前为止,这是我的想法。 (已经很晚了,所以我为愚蠢的错误道歉。)

public class Student
{
    public string StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    // Should this even be part of the Student POCO?
    public virtual ICollection<Exam> ExamsTaken { get; set; }
}

// I know this is right - putting it here to provide all the classes in question.
public class ExamStatus
{
    public int ExamStatusID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

// This is the POCO that really hangs me up.
public class Exam
{
    public int ExamID { get; set; }
    public int CourseID { get; set; }
    public string ExamTitle { get; set; }

    // Not sure if this should be part of Exam, or part of a different
    // object?
    public decimal? Score { get; set; }
    public int? ExamStatusID { get; set; }

    public virtual ICollection<Question> Questions { get; set; }
    public virtual Course Course { get; set; }
    public virtual ExamStatus ExamStatus { get; set; }
}

我很感激这种多对多关系的任何帮助(学生&lt; - &gt;考试)。我想我已经考虑得太多了,并且已经把自己弄得很糟糕,可能相当简单。

2 个答案:

答案 0 :(得分:2)

考试与考试结果分开。

因此将分数和状态拉出到单独的表格中。状态字段可能还希望包含已采用或待处理,以便您知道它们已经采用它但它正在等待标记(除非它全部自动完成)

通过这种方式,学生可以获得考试列表,该考试列表与分数表相关联,分数表与考试相关联。

答案 1 :(得分:2)

这就是我要改变的。我并不认为这正是亚当所说的。如果它让我知道,我将删除帖子

public class Student
{
    public string StudentID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    // changed this to results of the exams taken
    // you can still get exam via ExamResult -> Exam
    public virtual ICollection<ExamResult> ExamsTaken { get; set; }
}

public class Exam
{
    public int ExamID { get; set; }
    public int CourseID { get; set; }
    public string ExamTitle { get; set; }

    public virtual ICollection<Question> Questions { get; set; }
    public virtual Course Course { get; set; }
    // used to be ICollection of exam statuses, but that got moved to the
    // ExamResult class
    public virtual ICollection<ExamResults> Results { get; set; }
}

public class ExamResult
{
    public int ExamID { get; set; }
    public int StudentID { get; set; }

    public decimal? Score { get; set; }
    // all your results should have a status right? im assuming
    // unfinished or not started exams have statuses
    // so this shouldn't be nullable
    public int ExamStatusID { get; set; }

    public virtual Student Student { get; set; }
    public virtual Exam Exam { get; set; }
}