user10489212
user10489212

Reputation:

System.Data.SqlClient.SqlException: 'The INSERT statement conflicted with the FOREIGN KEY constraint

I'm still getting this error during debug. I'm not sure what to do, because I have added the AdddressID for the Person klass.

Please help!

The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Person_ToAddress\". The conflict occurred in database \"DirectoryDatabase\", table \"dbo.Address\", column 'AddressID'

The functions that throws this error is:

    public void CreatePersonDB(ref Person person)
    {
        string CreatePerson =
            @"INSERT INTO [Person] (FirstName, MiddleName, LastName, AddressID)
                                    OUTPUT INSERTED.PersonID  
                                    VALUES (@FName, @MName, @LName, @AID)";

        using (SqlCommand cmd = new SqlCommand(CreatePerson, OpenConnection))
        {
            // Get your parameters ready                    
            cmd.Parameters.AddWithValue("@FName", person.FirstName);
            cmd.Parameters.AddWithValue("@MName", person.MiddleName);
            cmd.Parameters.AddWithValue("@LName", person.LastName);
            cmd.Parameters.AddWithValue("@AID", person.PrimaryAddress.AddressID);

             try
            {
                person.PersonID = (int)cmd.ExecuteScalar(); //Returns the identity of the new tuple/record}
            }
            catch
            {
                Console.WriteLine("Adresse ID doesn't exist, do you want to add it? [y/n]");
                ConsoleKeyInfo input = Console.ReadKey();

                if (input.Key == ConsoleKey.Y)
                {
                    //create an insert query to the dbo.Adresse the same way you did with the dbo.person.
                    CreateAddressDB();
                }
        }
    }

The database sql code for Person & Address looks like this (after editing):

CREATE TABLE Address (
AddressID      BIGINT IDENTITY(1,1) NOT NULL,
StreetName     NVARCHAR(MAX) NOT NULL,
HouseNumber    NVARCHAR(MAX) NOT NULL,

CityID         BIGINT NOT NULL,

[PersonID] NCHAR(10) NOT NULL, [PrimaryAddress] INT NOT NULL, CONSTRAINT pk_Address PRIMARY KEY CLUSTERED (AddressID), CONSTRAINT fk_Address FOREIGN KEY (CityID) REFERENCES City (CityID) ON DELETE NO ACTION ON UPDATE NO ACTION)

This is for the Address table:

CREATE TABLE Person (
PersonID       BIGINT IDENTITY(1,1) NOT NULL,
FirstName      VARCHAR(50) NOT NULL,
MiddleName     NVARCHAR(50) NOT NULL,
LastName       NVARCHAR(50) NOT NULL,

AddressID      BIGINT NOT NULL,

CONSTRAINT pk_Person PRIMARY KEY CLUSTERED (PersonID), CONSTRAINT fk_Person FOREIGN KEY (AddressID) REFERENCES Address (AddressID) )

Upvotes: 4

Views: 8054

Answers (2)

Saber CHETIOUI
Saber CHETIOUI

Reputation: 50

You are trying to insert an AddressID to the Person table that doesn't exist in the Address table.

Try this instead:

public void CreatePersonDB(ref Person person)
{
    string CreatePerson =
        @"INSERT INTO [Person] (FirstName, MiddleName, LastName, AddressID)
                                OUTPUT INSERTED.PersonID  
                                VALUES (@FName, @MName, @LName, @AID)";

    using (SqlCommand cmd = new SqlCommand(CreatePerson, OpenConnection))
    {
        // Get your parameters ready                    
        cmd.Parameters.AddWithValue("@FName", person.FirstName);
        cmd.Parameters.AddWithValue("@MName", person.MiddleName);
        cmd.Parameters.AddWithValue("@LName", person.LastName);
        cmd.Parameters.AddWithValue("@AID", person.PrimaryAddress.AddressID);

        try()
        {
            person.PersonID = (int)cmd.ExecuteScalar();   // Returns the identity of the new tuple/record}
        catch()
        {
             DialogResult dialogResult = MessageBox.Show("Adresse ID doesn't exist, do you want to add it?", "Alerte",MessageBoxButtons.YesNo);

             if(dialogResult == DialogResult.Yes)
             {
                 // create an insert query to the dbo.Adresse the same way you did with the dbo.person.
             }
        }
    }
}

Upvotes: 0

Gavenko Sergey
Gavenko Sergey

Reputation: 31

In table dbo.Address doesn`t exists record with your person.PrimaryAddress.AddressID value

Upvotes: 2

Related Questions