参考实体框架中的数据库模型

时间:2015-01-14 00:14:51

标签: c# entity-framework

Question.cs

public class Question
{
    public int Id { get; set; }

    public string Text { get; set; }

    public int QuestionNr { get; set; }

    public string Image { get; set; }

    public Test Test { get; set; }

}

test.cs中

public class Test
{

    public int Id { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public int Public { get; set; }

    public int SubmittedTest { get; set; }

}

文件背后的代码

    protected void Submitquestionbtn_Click(object sender, EventArgs e)
    {
        var result = new QuestionService().AddQuestion(
             new Question()
             {
                 Text = questionText.Text,
                 QuestionNr = int.Parse(questionOrder.Text),
                 Image = "",
                 Test = **?????????????????????**
             });
        Response.Redirect("EditQuiz.aspx?success");
    }

我应该将测试称为什么?它是Test.Id的外键,但它引用了Test类(Test.cs)。 在数据库中,Test是一个int。但在问题类中,它是对Test类的引用。我怎样才能指出那个特定的对象?

1 个答案:

答案 0 :(得分:1)

这里有一堆错误......

首先,如果对象类也是Test,则无法命名对象Test的实例。

为了实例化一个Question实例,您可能需要类似以下的内容:

public class Question {
    public int Id { get; set; }
    public string Text { get; set; }
    public int QuestionNr { get; set; }
    public string Image { get; set; }
    public TestClass Test { get; set; }
}

public class TestClass {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int Public { get; set; }
    public int SubmittedTest { get; set; }
}


// for your event, when creating Question, just do the same for Test, embedded!
protected void Submitquestionbtn_Click(object sender, EventArgs e) {
    var result = new QuestionService().AddQuestion(
        new Question {
            Text = questionText.Text,
            QuestionNr = int.Parse(questionOrder.Text),
            Image = "",
            Test = new TestClass {
                Id = -1,
                Name = "",
                Description = "",
                Public = "",
                SubmittedTest = -1
            }
        }
    );
    Response.Redirect("EditQuiz.aspx?success");
}