私はスケジュールを含めて最初に選択するためのリストセミナーを作成した支払いセクションを介して、自分のWebサイトに外部キーを追加する方法を知りたいと思います。その後、ユーザーは登録をクリックし、ページをクレジットカードまたは現金を含む支払詳細フォームにリダイレクトすることができる。ユーザーが支払いを行い、確認ボタンをクリックすると、IDの主キー(自動生成)を含むデータベースが1つ増えます。ASP.NETでSQL Serverに外部キーを追加する方法C#
私の問題は、IDが-1であるために-1でもないID(データベースがSQL Serverで更新されていないことを確認しました)です。これは、あなたが追加する必要がありますあなたの答え ために、しかし、それを行うための良い方法ではありません
public static int purchaseSeminar(ShoppingCart sc)
{
int id = -1;
SqlConnection con = new SqlConnection(conStr);
try
{
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText = "insert into Payment (payment_id, payment_name, payment_ccNo, payment_ccType, payment_ccCode, payment_expDate, payment_price, payment_optionPay, payment_date, reg_id) values (@payment_id, @payment_name, @payment_ccNo, @payment_ccType, @payment_ccCode, @payment_expDate, @payment_price, @payment_optionPay, @payment_date, @reg_id)";
command.Parameters.AddWithValue("@payment_id", sc.Id);
command.Parameters.AddWithValue("@payment_ccNo", sc.CreditCard);
command.Parameters.AddWithValue("@payment_ccType", sc.CreditCardType);
command.Parameters.AddWithValue("@payment_ccCode", sc.SecurityCode);
command.Parameters.AddWithValue("@payment_expDate", sc.CCExpiryDate);
command.Parameters.AddWithValue("@payment_price", sc.TotalAmount);
command.Parameters.AddWithValue("@payment_optionPay", sc.OptionPay);
command.Parameters.AddWithValue("@reg_id", sc.Registration.RegId);
DateTime da = DateTime.Now;
command.Parameters.AddWithValue("@payment_date", da);
con.Open();
command.CommandText = "SET IDENTITY_INSERT Payment ON";
if (command.ExecuteNonQuery() > 0)
{
command.CommandText = "Select @@identity";
id = Convert.ToInt32(command.ExecuteScalar());
}
return id;
}
finally
{
con.Close();
}
}
"insert identity_insert ..."を実行するだけですので、 "set identity_insert ..."を実行してください。 –