在具有3个外键的数据库中插入记录

时间:2019-03-26 06:04:57

标签: asp.net

我正在尝试在表中插入一条记录,但是问题在于该表具有3个外键。我将为此使用dataTable,但是会给出错误“ 0没有行位置”

有我的代码:

 try
        {
            using (var sqlConnection = new Helpers.SqlConnectionHelpers())
            {
                var connection = sqlConnection.OpenConnection();


                command = new SqlCommand("CarSold_Insert", connection);
                command.CommandType = CommandType.StoredProcedure;

                SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = '" + txtPrice.Text + "'", connection);
                DataTable table = new DataTable();
                DataSet dataSet = new DataSet();
                table.Load(commandTwo.ExecuteReader());
                var carForSaleId = table.Rows[0]["CarForSaleId"].ToString();
                var userId = table.Rows[0]["UserId"].ToString();
                var salesPersonId = table.Rows[0]["SalesPersonId"].ToString();

                command.Parameters.AddWithValue("CarForSaleId", carForSaleId);
                command.Parameters.AddWithValue("UserId", userId);
                command.Parameters.AddWithValue("SalesPersonId", salesPersonId);
                command.Parameters.AddWithValue("Price", txtPrice.Text);
                command.Parameters.AddWithValue("DateSold", dateSold);
                command.Parameters.AddWithValue("MonthlyPaymentDate", monthlyPaymentDate);
                command.Parameters.AddWithValue("MonthlyPaymentAmount", txtPaymentAmount.Text);
                //connection.Open();
                int k = command.ExecuteNonQuery();
                command.Parameters.Clear();
                if (k != 0)
                {
                    Response.Redirect("~/AdminPanel/CarSold.aspx");
                }
                else
                {
                    lblAns.Text = "Record Not Inserted into the database";
                    lblAns.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        catch (Exception ex)
        {
            lblAns.Text = ex.Message;
        }

1 个答案:

答案 0 :(得分:0)

由于“价格”列是浮动的,因此您需要使用以下查询参数编写查询:

SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = @Price", connection);
commandTwo.Parameters.AddWithValue("@Price", txtPrice.Text);

上述命令将返回carForSaleIduserIdsalesPersonId,您将在插入命令中使用