4

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) )

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Possible duplicate of [INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server](https://stackoverflow.com/questions/2965837/insert-statement-conflicted-with-the-foreign-key-constraint-sql-server) – Anas Alweish Oct 11 '18 at 11:00
  • I read this thread, but I couldnt figured out in order to fix my code. –  Oct 11 '18 at 11:06

2 Answers2

2

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

0

Your are trying to insert an AdresseID to the person table that doesn't exist in the Adresse 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.
             }
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Saber CHETIOUI
  • 50
  • 1
  • 13
  • So I have to add PrimaryAddress as well as AddressID to the dbo.Address? –  Oct 11 '18 at 11:02
  • 1
    Yes, try to catch that exception in order to allow you to create a new AdressID record to the dbo.Adresse and then continue inserting to the dbo.Person. – Saber CHETIOUI Oct 11 '18 at 11:12
  • Thanks @Saber, I have updated the question with changes you suggested, but i still get errors as the function is not recognizable. –  Oct 11 '18 at 12:12
  • 1
    you already solved it in your first comment as you said, start inserting AdresseID in the dbo.Adresse table and then to the dbo.Person, what I proposed after may requires function that doesn't work in console application, if it still does'nt work, send more details including dbo.person and dbo.adresse actual records – Saber CHETIOUI Oct 11 '18 at 17:41