Mayank Mishra
Mayank Mishra

Reputation: 25

How to insert foreign key value in Child table in c#

i am trying to fill a foreign key value in child table with using parametric insert query statically i get success but when i am trying to do it dynamically it does not work

my parent table is Customer custId(pk),CustName,contact are the fields there

and child table is _order orderId(pk),item,qauntity,cust_Id(fk) are filelds

my code for insertion in c# is:

SqlCommand scmd = new SqlCommand("insert into Customer (custname,contact)values(@custname,@contact)", conn);
                scmd.Parameters.AddWithValue("@custname", cusname.Text);
                scmd.Parameters.AddWithValue("@contact", contact.Text);
                scmd.ExecuteNonQuery();

  SqlCommand scmd1 = new SqlCommand("insert into  _order (item,qauntity,cust_Id) select @item,@qauntity,custId from Customer where custId= @custId", conn);
                scmd1.Parameters.AddWithValue("@item", item.Text);
                scmd1.Parameters.AddWithValue("@qauntity", qauntity.Text);
                scmd1.ExecuteNonQuery();

when i give a hard code value in second query on where condition it works but how to do it dynamically i think everyone understand my problem please help thanks

Upvotes: 0

Views: 4913

Answers (1)

b0bi
b0bi

Reputation: 628

Try it:

SqlCommand scmd = new SqlCommand("insert into Customer (custname,contact)values(@custname,@contact); SELECT SCOPE_IDENTITY()", conn);
scmd.Parameters.AddWithValue("@custname", cusname.Text);
scmd.Parameters.AddWithValue("@contact", contact.Text);
int custId = Convert.ToInt32(scmd.ExecuteScalar());

SqlCommand scmd1 = new SqlCommand("insert into  _order (item,qauntity,cust_Id) VALUES(@item,@qauntity,@custId)", conn);
scmd1.Parameters.AddWithValue("@item", item.Text);
scmd1.Parameters.AddWithValue("@qauntity", qauntity.Text);
scmd1.Parameters.AddWithValue("@custId", custId);
scmd1.ExecuteNonQuery();

Upvotes: 1

Related Questions