对于一项学校作业,我想制作一个小型问卷式网站,您可以在其中输入多个问题并将它们添加到考试中。
我使用的技术是 MVC 和 Entity Framework(代码优先)。对于两者来说,这是我第一次独自骑行,没有教程之类的,我似乎陷入了我的模型设计(那些将用于数据库的模型)。
我想要一个包含多个问题
的考试
表。据我了解,这应该是一个集合(研究说使用这个,但我不确定这是正确的)。
在这种情况下,我该如何设置 Exam
模型,以便它包含多个 Question 对象
并且也可以被 Entity Frameworks 的 Code First 使用?
这是我现在拥有的:
public class Exam
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreationDate { get; set; }
public ICollection<Question> Questions { get; set; }
}
public class Question
{
public enum Answers
{
A,
B,
C,
D
}
public int Id { get; set; }
public string Name { get; set; }
public string AnswerA { get; set; }
public string AnswerB { get; set; }
public string AnswerC { get; set; }
public string AnswerD { get; set; }
public Answers Correct { get; set; }
}
最佳答案
你可能想像这样添加到你的问题属性中:
[ForeignKey("Exam")]
public int ExamId { get; set; }
public virtual Exam Exam { get; set; }
如果你想控制外键。
并且您可以添加 virtual 关键字以在您的考试类中启用延迟加载:
public virtual ICollection<Question> Questions { get; set; }
关于c# - Entity Framework 代码第一个对象引用多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25886398/