Reputation:
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
, tableRestaurantApp.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)
Upvotes: 2
Views: 1885
Reputation: 225
By viewing your question, it seems that your insert query is not correct:
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();
Upvotes: 2