Sqlite foreign key constraint failed when adding products

  Kiến thức lập trình

When I try to insert a product from my ProductDetails table with seller_id from Sellers Table as its relationship, it says foreign key constraint failed.

For example, in my UI there is to add the name of the product, its category, price, description, and picture. Attempting to add product will cause foreign key constraint failed.

P.S: I’m a newbie to sql database because im a student, any help is a big appreciation for my school project… 🙂

//Initializing for Seller Accounts Database
 public async static void InitializeDB_SELLERACCOUNTS()
 {
     await ApplicationData.Current.LocalFolder.CreateFileAsync("MyDatabase.db", CreationCollisionOption.OpenIfExists);
     string pathtoDB = Path.Combine(ApplicationData.Current.LocalFolder.Path, "MyDatabase.db");

     using (SqliteConnection con = new SqliteConnection($"Filename={pathtoDB}"))
     {
         con.Open();
         string initCMD = @"CREATE TABLE IF NOT EXISTS Sellers (
                     SELLER_ID INTEGER PRIMARY KEY AUTOINCREMENT,                        
                     BusinessName TEXT NOT NULL,
                     Email TEXT NOT NULL,
                     Username TEXT NOT NULL,
                     LastName TEXT NOT NULL,
                     FirstName TEXT NOT NULL,
                     MiddleName TEXT NOT NULL,
                     Password TEXT NOT NULL,
                     PhoneNumber TEXT NOT NULL,
                     AddressLine1 TEXT NOT NULL,
                     AddressLine2 TEXT NOT NULL
                   )";

         SqliteCommand CMDcreateTable = new SqliteCommand(initCMD, con);
         CMDcreateTable.ExecuteReader();
         con.Close();
     }
 }  
public async static void InitializeDB_PRODUCTDETAILS()
  {
      await ApplicationData.Current.LocalFolder.CreateFileAsync("MyDatabase.db", CreationCollisionOption.OpenIfExists);
      string pathtoDB = Path.Combine(ApplicationData.Current.LocalFolder.Path, "MyDatabase.db");

      using (SqliteConnection con = new SqliteConnection($"Filename={pathtoDB}"))
      {
          con.Open();
          string initCMD = @"CREATE TABLE IF NOT EXISTS ProductDetails (
                      PRODUCTDETAILS_ID INTEGER PRIMARY KEY AUTOINCREMENT,
                      Seller_ID INTEGER NOT NULL,
                      ProductName TEXT NOT NULL,
                      ProductCategory TEXT,
                      ProductPrice REAL,
                      ProductDescription TEXT,
                      ProductQuantity INTEGER,
                      ProductPicture BLOB,
                      ProductSKU INTEGER NOT NULL,
                      FOREIGN KEY (Seller_ID) REFERENCES Sellers (SELLER_ID)  
                    )";

          SqliteCommand CMDcreateTable = new SqliteCommand(initCMD, con);
          CMDcreateTable.ExecuteReader();
          con.Close();
      }
  }


  // Adding Product to the Database
  public static void AddProduct(int seller_id, string productname, string productcategory, double productprice, string productdescription, int productquantity, byte[] productpicture)
  {
      string pathtoDB = Path.Combine(ApplicationData.Current.LocalFolder.Path, "MyDatabase.db");

      using (SqliteConnection con = new SqliteConnection($"Filename={pathtoDB}"))
      {
          con.Open();

          // Generate a random 12-digit SKU
          Random random = new Random();
          long productSKU;
          bool isUniqueSKU = false;

          // Loop until a unique SKU is generated
          do
          {
              productSKU = (long)(random.NextDouble() * (999999999999L - 100000000000L) + 100000000000L);
              string checkSKUQuery = "SELECT COUNT(*) FROM ProductDetails WHERE ProductSKU = @ProductSKU";

              using (SqliteCommand cmdCheckSKU = new SqliteCommand(checkSKUQuery, con))
              {
                  cmdCheckSKU.Parameters.AddWithValue("@ProductSKU", productSKU);
                  long existingCount = (long)cmdCheckSKU.ExecuteScalar();

                  if (existingCount == 0)
                      isUniqueSKU = true;
              }
          } while (!isUniqueSKU);

          string insertCMD = @"INSERT INTO ProductDetails (Seller_ID, ProductSKU, ProductName, ProductCategory, ProductPrice, ProductDescription, ProductQuantity, ProductPicture) 
                       VALUES (@Seller_ID, @ProductSKU, @ProductName, @ProductCategory, @ProductPrice, @ProductDescription, @ProductQuantity, @ProductPicture)";

          SqliteCommand cmdInsertRecord = new SqliteCommand(insertCMD, con);
          cmdInsertRecord.Parameters.AddWithValue("@Seller_ID", seller_id);
          cmdInsertRecord.Parameters.AddWithValue("@ProductName", productname);
          cmdInsertRecord.Parameters.AddWithValue("@ProductCategory", productcategory);
          cmdInsertRecord.Parameters.AddWithValue("@ProductPrice", productprice);
          cmdInsertRecord.Parameters.AddWithValue("@ProductDescription", productdescription);
          cmdInsertRecord.Parameters.AddWithValue("@ProductQuantity", productquantity);
          cmdInsertRecord.Parameters.AddWithValue("@ProductPicture", productpicture);
          cmdInsertRecord.Parameters.AddWithValue("@ProductSKU", productSKU);

          cmdInsertRecord.ExecuteNonQuery();
          con.Close();
      }
  }

I tried switching the columns by still dosen’t work.

LEAVE A COMMENT