简体   繁体   中英

Referring to Database model in 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; }

}

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? It's a foreign key to Test.Id but it refers to the Test class (Test.cs). In the database Test is an int. But in the questionclass it's a reference to the Test class. 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.

For you to instantiate an instance of Question, you likely need something similar to the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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