how to add autofill foreign key values in C# sql
Ado connectivity
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
how to add autofill foreign key values in C# sql
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Sachin SinghRank #66 · 26.2K reputationPosted Sep 18, 2022, 3:49 AM EDT
Foreign key (Let's say for Table_A) means primary key of another table (Let's say Table_B). So if Table_B has multiple rows then it will have multiple PK values, So, Table_A FK column should have only those values which are present in Table_B primary key column.
So, when you insert a row in Table_B you can fetch the last PK value using Scope_Identity() and can insert it into FK column in Table_A.
using(SqlConnection con= new SqlConnection(cs)) { SqlCommand cmd= new SqlCommand(@"Declare @FKId INT;Insert into Table_B(col2,col3) values (@param1,@param2);Select @FKId=Scope_Identity(); Insert into Table_A (col2,col3)values(@Param3,@param4)"); cmd.parameters.AddWithValue("@Param1",param1Value); cmd.parameters.AddWithValue("@Param2",param2Value); cmd.parameters.AddWithValue("@Param3",param3Value); cmd.parameters.AddWithValue("@Param4",param4Value); con.Open(); cmd.ExecuteNonQuery(); }But, i will suggest you to use Stored procedure instead.