c# - Entity Framework 代码第一个对象引用多个对象

标签 c# asp.net-mvc entity-framework

对于一项学校作业,我想制作一个小型问卷式网站,您可以在其中输入多个问题并将它们添加到考试中。

我使用的技术是 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/

相关文章:

c# - csom 上下文凭据安全

c# - 测试类 - 何时重构?

c# - ASP.NET MVC3 从部分 View 上传文件(并填写模型中的相应字段)

c# - T4MVC 不适用于 Url.Action()

c# - Entity Framework 一对多自引用关系

c# - 如果在实例化 DbContext 资源的 using 语句中数据库连接失败,我如何自动抛出 ApplicationException?

c# - DataGridViewCheckBoxCell 点击处理问题

c# - 比手动字典更好的选项来引用其中正在运行的方法的 'current task'?

c# - 将数据库上传到 ASP.NET MVC 应用程序的服务器?

Asp.net web api + Entity Framework : multiple requests cause data conflict