简体   繁体   English

如何在C#中的子表中插入外键值

[英]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我的父表是Customer custId(pk),CustName,contact 是那里的字段

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

my code for insertion in c# is:我在 c# 中插入的代码是:

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当我在第二次查询中给出一个硬代码值时,它在什么条件下工作,但如何动态地做,我想每个人都理解我的问题,请帮助谢谢

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM