SQL - MVC - Insert into 2 tables
im working in mvc and use sql command to insert data to my database.
what i try to do is insert into 2 tables which one of them have the
foreign key from the other.
how can i build my sql query to make a condition on insert into the table
Image, insert the id in the foreignkey column in the table Content.
using (SqlConnection cn = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("insert into Image(FileName)");
sql.Append("values (@FileName)");
SqlCommand cmd2;
System.Text.StringBuilder sql2 = new System.Text.StringBuilder();
sql.Append("insert into Code(Html,JsCode,Id_Img)");
sql.Append("values (@Html, @JsCode, @Id_Img)");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add("@FileName", SqlDbType.VarChar).Value = myfilename;
int FileId = (int)cmd.ExecuteScalar();
cmd2 = new SqlCommand(sql2.ToString(), cn);
cmd2.Parameters.Add("@Html", SqlDbType.VarChar).Value = mydiv;
cmd2.Parameters.Add("@JsCode", SqlDbType.VarChar).Value = DBNull.Value;
cmd2.Parameters.Add("@Id_Img", SqlDbType.Int).Value = FileId;
cmd2.ExecuteNonQuery();
cn.Close();
}
No comments:
Post a Comment