简体   繁体   English

在实体框架中引用数据库模型

[英]Referring to Database model in Entity Framework

Question.cs 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 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; }

}

Code behind file 文件后面的代码

    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");
    }

What should I refer Test to? 我应该向Test推荐什么? It's a foreign key to Test.Id but it refers to the Test class (Test.cs). 这是Test.Id的外键,但它引用了Test类(Test.cs)。 In the database Test is an int. 在数据库中Test是一个int。 But in the questionclass it's a reference to the Test class. 但是在questionclass中,它是对Test类的引用。 How can I point at that specific object? 我如何指向该特定对象?

There a bunch of stuff wrong going on here... 这里发生了很多错误...

First you can't name the instance of your object Test, if your object class is also Test. 首先,如果您的对象类也是Test,则无法命名对象Test的实例。

For you to instantiate an instance of Question, you likely need something similar to the following: 为了实例化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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM