Оператор INSERT конфликтует с ограничением FOREIGN KEY "FK_, но первичный ключ действительно существует в родительской таблице - PullRequest
0 голосов
/ 06 октября 2019

Две таблицы: Table1 (родительский) имеет первичный ключ, Table2 (дочерний) имеет внешний ключ, который ссылается на первичный ключ Table1. После вставки данных в Table2, после того, как я вставил данные в Table1, я получаю SQLException:

Оператор INSERT конфликтует с ограничением FOREIGN KEY "FK_.

Прежде чем выполнить код для вставки данных в таблицу 2, я проверяю, существует ли первичный ключ - который будет внешним ключом таблицы 2. Есть ли какая-либо другая причина для этого исключения, кроме очевидной причины отсутствия значенияв родительской таблице, хотя я делаю. Спасибо

Я попытался вставить данные в SQL Server Management Studio вместо их вставки через код ASP.NET, используя тот же оператор SQL, но с определенными значениями.

// Check to see if `VenueID` exists which does exist because the 
// dt.rows.count is greater than 0 and do something gets executed.
SqlCommand select = new SqlCommand("SELECT VenueID FROM IBTCVenue WHERE VenueID = @VenueID", con);

select.Parameters.AddWithValue("@VenueID", VenueID);

DataTable dt = new DataTable();
SqlDataAdapter dql = new SqlDataAdapter(select);
dql.Fill(dt);

if (dt.Rows.Count > 0)
{
     --do something--
}

// VenueID is retrieved from another method using 
// SELECT @id = SCOPE_IDENTITY() upon insertion of Venue.


 protected void BookCourseMethod(int ClientID, int BoomakerID, int VenueID)
    {
        SqlCommand insert = new SqlCommand("insert into IBTCCourse(Visible, SDate,EDate,NumOfAttendees,VenueID,ClientID,BookMakerID,Time_stamp,EventID) values(@Visible,@SDate,@EDate,@NumOfAttendees,@ClientID,@VenueID,@BookMakerID,@timestamp,@EventID)", con);
        SqlCommand select = new SqlCommand("Select VenueID from IBTCVenue where VenueID = @VenueID", con);

        select.Parameters.AddWithValue("@VenueID", VenueID);
        DataTable dt = new DataTable();
        SqlDataAdapter dql = new SqlDataAdapter(select);
        dql.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            string DropDownValue = Request.Form["DropDownList2"];
            DateTime Sdate = Convert.ToDateTime(Request.Form["SDate"]);
            DateTime Edate = Convert.ToDateTime(Request.Form["EDate"]);
            string NumOfAttendees = Request.Form["attendees"];
            string EventID = DropDownValue.Split(',')[0];
            // string Title = DropDownValue.Split(' ')[1];

            insert.Parameters.AddWithValue("@VenueID", VenueID);
            insert.Parameters.AddWithValue("@EventID", EventID);
            insert.Parameters.AddWithValue("@BookMakerID", BoomakerID);
            // insert.Parameters.AddWithValue("@Title", Title);
            insert.Parameters.AddWithValue("@NumOfAttendees", NumOfAttendees);
            insert.Parameters.AddWithValue("@SDate", Sdate);
            insert.Parameters.AddWithValue("@EDate", Edate);
            insert.Parameters.AddWithValue("@ClientID", ClientID);
            insert.Parameters.AddWithValue("@timestamp", DateTime.Now);
            insert.Parameters.AddWithValue("@Visible", "True");


            try
            {

                con.Close();
                con.Open();
                int succes = insert.ExecuteNonQuery();
                if (succes == 1)
                {
                    //  Response.Write("<script>alert('The Event has been succesfully booked')</script>");
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "test", "alert('The Event has been succesfully booked');", true);
                    //clientemailLbl.Text = "";
                    //lblCell.Text = "";
                    //lblFax.Text = "";
                    //lblTel.Text = "";
                    SDate.Text = "";
                    EDate.Text = "";
                    BookieemailLbl.Text = "";
                    BookieFaxLbl.Text = "";
                    BookiecellLbl.Text = "";
                    BookieemailLbl.Text = "";
                    BookieFaxLbl.Text = "";
                    BookiecellLbl.Text = "";
                    //clientemailLbl.Text = "";
                    //lblCell.Text = "";
                    //lblFax.Text = "";
                    //lblTel.Text = "";
                 //   DropDownList2.SelectedIndex = 0;
                    DropDownList3.SelectedIndex = 0;
                    clientName.Text = "";
                    clientsurname.Text = "";
                    //clientemail.Text = "";
                    //Cell.Text = "";
                    //Fax.Text = "";
                    //Tell.Text = "";
                    Bookiename.Text = "";
                    Bookiesurname.Text = "";
                    Bookieemail.Text = "";
                    BookieFax.Text = "";
                    Bookiecell.Text = "";
                    //   userLbl.Text = "";
              //      Label1.Text = "";
                    //RequiredFieldValidator5.Visible = true;
                    //lblTel.Visible = false;
                    //clientemailLbl.Visible = false;
                    //RequiredFieldValidator2.Visible = true;
                    //RequiredFieldValidator3.Visible = true;
                    //lblCell.Visible = false;
                    //RequiredFieldValidator4.Visible = true;
                    //lblFax.Visible = false;
                    //RequiredFieldValidator5.Visible = true;
                    //lblTel.Visible = false;
                    sdtlbl.Visible = true;
                    RequiredFieldValidator6.Visible = true;
                    RequiredFieldValidator12.Visible = true;
                    RequiredFieldValidator13.Visible = true;
                //    attendees.Text = "";
                }
            }
            catch
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "test", "alert('ERROR 101 : Please Contact Web Administator');", true);
                //Response.Write("<script>alert('ERROR 101 : Please Contact Web Administator')</script>");
            }

            finally
            {
                con.Close();
            }
        }


    }
...