c# - How to insert data into sql server database when the primary key column already set default identity(1, 1) -
i'm trying insert 2 data columns sql server database error @ code line -> cmd.executenonquery();
cannot insert value null column
orderid
, tablerestaurantapp.dbo.junc_order
; column not allow nulls. insert fails.
the orderid
column primary key in data table. set identity(1, 1) , want insert other data , meanwhile can insert 1, 2, 3, 4....automatically.
here part of code:
string insertstring = "insert 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 connection database ahead of these codes, problem should not that.
updated junc_order table design:
orderid (pk,fk,int,not null) id(fk,int,not null) quantity(int,not null)
by viewing question, seems insert query not correct:
- first of all, don't need insert "orderid" primary key identity sql server automatically insert it.
second, somewhere getting "r_id" null that's why facing error.verify , modify code following:
string insertstring = "insert junc_order(quantity) values(@quantity)"; sqlcommand cmd = new sqlcommand(insertstring, conn); cmd.parameters.addwithvalue("@quantity", r_quantity); cmd.executenonquery();
Comments
Post a Comment