FOREIGN KEY约束问题,即使值已存在

时间:2014-10-31 14:54:33

标签: c# sql visual-studio-2012 foreign-keys

我在发布之前已经研究过各种解决方案作为我的最后一招。我似乎无法弄清楚代码究竟发生了什么。该值将插入到1个表中,但是当我插入另一个表时,它会给出错误“INSERT语句与FOREIGN KEY约束冲突”FK_QuizAnswer_ToQuiz“。”。

当我插入它时,数据库中已存在该值,我知道这是因为我已经测试从数据库中检索值并将其分配给标签,即使我这样做也会得到相同的错误。请帮忙。

ASPX页面

<asp:MultiView ID="MultiView1" ActiveViewIndex="0" runat="server">
            <asp:View ID="View1" runat="server">
                <table>
                    <tr>
                        <td>
                            <asp:Label ID="QuizName" runat="server" Text="Quiz Name: "></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="QuizNameTextBox" Placeholder="Enter Quiz Name" runat="server"></asp:TextBox>
                            <asp:Label ID="nameerror" runat="server" ForeColor="Red" Visible="false" Text="The quiz name already exists, please create another."></asp:Label>
                            <asp:RequiredFieldValidator ID="QuizNameRequired" ForeColor="Red" Display="Dynamic" ControlToValidate="QuizNameTextBox" runat="server" ErrorMessage="The quiz name is required."></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="ForCourse" runat="server" Text="For Course: "></asp:Label>
                        </td>
                        <td>
                            <asp:DropDownList ID="DropDownList1" runat="server">
                                <asp:ListItem value="1">Course51531</asp:ListItem>
                                <asp:ListItem value="7">Course6</asp:ListItem>
                                <asp:ListItem value="9">Course8</asp:ListItem>
                                <asp:ListItem value="12">Course 11</asp:ListItem>
                                <asp:ListItem value="35">Course 1sdwd</asp:ListItem>
                                <asp:ListItem value="36">ewfwef</asp:ListItem>
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Reattempt" runat="server" Text="Can this be re-attempted?: "></asp:Label>
                        </td>
                        <td>
                            <asp:RadioButtonList AutoPostBack="true" ID="Reattemptradio" runat="server">
                                <asp:ListItem Text="Yes" Value="Yes"></asp:ListItem>
                                <asp:ListItem Text="No" Value="No"></asp:ListItem>
                            </asp:RadioButtonList>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="Reattemptradio" Display="Dynamic" ForeColor="Red" runat="server" ErrorMessage="Please select a value."></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Reattemp1" Visible="false" runat="server" Text="How many times?: "></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="reattemptbox1" Visible="false" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <asp:Button ID="Continue" CommandName="SwitchViewByID" CommandArgument="View2" ToolTip="Click here to create questions for the quiz." runat="server" Text="Continue" OnClick="Continue_Click" />
                        </td>
                    </tr>
                </table>
            </asp:View>
            <asp:View ID="View2" runat="server">
                <table>
                    <tr>
                        <td>
                            <asp:Label ID="Label1" runat="server" Text="Question No: "></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Label2" runat="server" Text="Question Name"></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Label3" runat="server" Text="Question Type:"></asp:Label>
                        </td>
                        <td>
                            <asp:DropDownList ID="DropDownList2" runat="server">
                                <asp:ListItem Text="---Select---" Value="---Select---"></asp:ListItem>
                                <asp:ListItem Text="Drop Down Menu" Value="Drop Down Menu"></asp:ListItem>
                                <asp:ListItem Text="Radio Buttons" Value="Radio Buttons"></asp:ListItem>
                                <asp:ListItem Text="Check Box" Value="Check Box"></asp:ListItem>
                                <asp:ListItem Text="TextBox" Value="TextBox"></asp:ListItem>
                                <asp:ListItem Text="Multi Line Response" Value="Multi Line Response"></asp:ListItem>
                            </asp:DropDownList>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="Label4" runat="server" Text="Pass Mark: "></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                        </td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>
                            <asp:Button ID="Button1" CommandName="SwitchViewByID" CommandArgument="View3" OnClick="Button1_Click" runat="server" Text="Button" />
                        </td>
                    </tr>
                </table>
            </asp:View>
            <asp:View ID="View3" runat="server">
                <table>
                    <tr>
                        <td>
                            <asp:Label ID="ResponseLabel11" runat="server" Text="Enter another Response: "></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="ResponseTextBox11" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator5" ControlToValidate="ResponseTextBox11" Display="Dynamic" ForeColor="Red" runat="server" ErrorMessage="A response is required."></asp:RequiredFieldValidator>
                        </td>
                        <td>Note: The response in this textbox should be an answer.
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:Label ID="ResponseLabel12" runat="server" Text="Enter another Response: "></asp:Label>
                        </td>
                        <td>
                            <asp:TextBox ID="ResponseTextBox12" runat="server"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator7" ControlToValidate="ResponseTextBox12" Display="Dynamic" ForeColor="Red" runat="server" ErrorMessage="Another response is required."></asp:RequiredFieldValidator>
                        </td>
                        <td>
                            <asp:CheckBox ID="Answer12" Text="Is Answer?" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <asp:Button ID="Button2" OnClick="Button2_Click" runat="server" Text="Button" />
                        </td>
                    </tr>
                </table>
            </asp:View>
        </asp:MultiView>

c#文件

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
int quizid = 0;
int check = 0;
int questid = 0;
int counter = 1;
int count = 0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreRender(object sender, EventArgs e)
{

}
protected void Continue_Click(object sender, EventArgs e)
{
    DropDownList1.SelectedValue = DropDownList1.SelectedValue;
    using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        connection.Open();
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "INSERT INTO [Quiz] ([QuizName], [CourseId], [AllowedAttempts]) VALUES (@QuizName, @CourseId, @AllowedAttempts)";
            command.Parameters.AddWithValue("@QuizName", SqlDbType.NVarChar).Value = QuizNameTextBox.Text;
            command.Parameters.AddWithValue("@CourseId", SqlDbType.Int).Value = Convert.ToInt32(DropDownList1.SelectedValue.ToString());
            if (Reattemptradio.SelectedValue.ToString() == "Yes")
            {
                command.Parameters.AddWithValue("@AllowedAttempts", SqlDbType.Int).Value = Convert.ToInt32(reattemptbox1.Text);
                command.ExecuteNonQuery();
            }
            else
            {
                command.Parameters.AddWithValue("@AllowedAttempts", SqlDbType.Int).Value = 0;
                command.ExecuteNonQuery();
            }
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        connection.Open();
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "SELECT QuizId FROM Quiz WHERE (QuizName = '" + QuizNameTextBox.Text + "')";
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    quizid = Convert.ToInt32(reader["QuizId"]);
                    ViewState["quiz"] = quizid;
                }
            }
        }
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "INSERT INTO [QuizQuestion] ([QuizId], [QuestionNo], [QuestionType], [QuestionName], [QuestionMark]) VALUES (@QuizId, @QuestionNo, @QuestionType, @QuestionName, @QuestionMark)";
            command.Parameters.AddWithValue("@QuizId", SqlDbType.Int).Value = quizid;
            command.Parameters.AddWithValue("@QuestionNo", SqlDbType.Int).Value = TextBox1.Text;
            command.Parameters.AddWithValue("@QuestionName", SqlDbType.NVarChar).Value = TextBox2.Text;
            command.Parameters.AddWithValue("@QuestionType", SqlDbType.NVarChar).Value = DropDownList2.SelectedValue.ToString();
            command.Parameters.AddWithValue("@QuestionMark", SqlDbType.NVarChar).Value = TextBox4.Text;
            command.ExecuteNonQuery();

        }
    }
}
protected void Button2_Click(object sender, EventArgs e)
{
    ViewState["count"] = Convert.ToInt32(ViewState["count"]) + counter + 1;
    using (var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        connection.Open();
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "SELECT QuizQuestionId FROM QuizQuestion WHERE (QuestionName = '" + TextBox2.Text + "')";
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    questid = Convert.ToInt32(reader["QuizQuestionId"].ToString());
                }
            }
        }
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "INSERT INTO [QuizAnswer] ([QuizId], [QuizQuestionId], [Response], [Sequence], [CorrectResponse]) VALUES (@QuizId, @QuizQuestionId, @Response, @Sequence, @CorrectResponse)";
            command.Parameters.AddWithValue("@QuizId", SqlDbType.Int).Value = Convert.ToInt32(ViewState["quiz"]);
            command.Parameters.AddWithValue("@QuizQuestionId", SqlDbType.Int).Value = Convert.ToInt32(questid);
            command.Parameters.AddWithValue("@Response", SqlDbType.NVarChar).Value = ResponseTextBox11.Text;
            command.Parameters.AddWithValue("@Sequence", SqlDbType.Int).Value = count;
            command.Parameters.AddWithValue("@CorrectResponse", SqlDbType.Bit).Value = Convert.ToBoolean("True");
            command.ExecuteNonQuery();
        }
    }
}}

QuizAnswer表

CREATE TABLE [dbo].[QuizAnswer] 
(
    [QuizAnswerId]    INT            IDENTITY (1, 1) NOT NULL,
    [QuizQuestionId]  INT            NOT NULL,
    [QuizId]          INT            NOT NULL,
    [Response]        NVARCHAR (MAX) NOT NULL,
    [Sequence]        INT            NOT NULL,
    [CorrectResponse] BIT            DEFAULT ((0)) NOT NULL,

    PRIMARY KEY CLUSTERED ([QuizAnswerId] ASC),
    CONSTRAINT [FK_QuizAnswer_ToQuizQuestion] 
        FOREIGN KEY ([QuizQuestionId]) REFERENCES [dbo].[QuizQuestion] ([QuizQuestionId]),
    CONSTRAINT [FK_QuizAnswer_ToQuiz] 
        FOREIGN KEY ([QuizId]) REFERENCES [dbo].[Quiz] ([QuizId])
);

测验表

CREATE TABLE [dbo].[Quiz] 
(
    [QuizId]          INT           IDENTITY (1, 1) NOT NULL,
    [QuizName]        NVARCHAR (50) NOT NULL,
    [CourseId]        INT           NOT NULL,
    [TotalMarks]      INT           DEFAULT ((1)) NULL,
    [PassMarks]       INT           NULL,
    [AllowedAttempts] INT           DEFAULT ((0)) NOT NULL,
    [IsActive]        BIT           DEFAULT ((0)) NOT NULL,

    PRIMARY KEY CLUSTERED ([QuizId] ASC),
    CONSTRAINT [FK_Quiz_ToCourse] 
        FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Course] ([CourseId])
);

3 个答案:

答案 0 :(得分:0)

当您尝试将答案存储到Button2_Click事件中的QuizAnswer表中时,看起来您正在从ViewState中提取QuizId:

command.Parameters.AddWithValue("@QuizId", SqlDbType.Int).Value = Convert.ToInt32(ViewState["quiz"]);

您可能希望此时设置一个断点,并确保QuizId值实际上正确返回或者在回发期间丢失了。

答案 1 :(得分:0)

问题很可能出现在该行中:

command.Parameters.AddWithValue("@QuizId", SqlDbType.Int).Value = Convert.ToInt32(ViewState["quiz"]);

要么在此行之外设置断点,以查看您的参数值也被分配了什么,或者运行sql profiler以查看实际传入的内容。

您可能无法正确地将quizId分配给ViewState["quiz"]

答案 2 :(得分:0)

您可以使用Button2的CommandArgument属性将QuizID附加到它。

<asp:Button ID="Button2" OnCommand="Button2_Click" runat="server" Text="Button" />    

然后方法如下:

protected void Button2_Click(object sender, CommandEventArgs e)

Button1_Click中,您可以像这样分配quizId:

Button2.CommandArgument = quizid;

问题的一般原因可能是ViewState受到在视图之间切换的代码的影响。每次视图更改时,都会发布回发。这可以解释为什么ViewState不再保留该值。