How to insert data into sql server database when the primary key column already set default identity(1, 1)

1.8k Views Asked by At

I'm trying to insert two data columns into my SQL Server database but I get an error at the code line -> cmd.ExecuteNonQuery();

Cannot insert the value NULL into column OrderID, table RestaurantApp.dbo.Junc_Order; column does not allow nulls. INSERT fails.

The OrderID column is actually the primary key in my data table. I set it identity(1, 1) and want to insert other data and meanwhile it can insert 1, 2, 3, 4....automatically.

Here is the part of my code:

string insertString = "INSERT INTO Junc_Order(ID, Quantity)values (@ID, @Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("@ID", r_ID);
cmd.Parameters.AddWithValue("@Quantity", r_Quantity);
cmd.ExecuteNonQuery();

I already get connection with database ahead of these codes, so the problem should not be that.

Updated Junc_Order table design:

OrderID (PK,FK,int,not null)

ID(FK,int,not null)

Quantity(int,not null)
1

There are 1 best solutions below

2
On BEST ANSWER

By viewing your question, it seems that your insert query is not correct:

  1. First of all, you don't need to insert "OrderID" as it is primary key identity so sql server automatically insert it.
  2. second, somewhere you are getting "r_ID" as null that's why you are facing error.Verify it and modify your code with the following:

    string insertString = "INSERT INTO Junc_Order(Quantity) values(@Quantity)"; SqlCommand cmd = new SqlCommand(insertString, conn); cmd.Parameters.AddWithValue("@Quantity", r_Quantity); cmd.ExecuteNonQuery();