【发布时间】:2017-11-16 07:14:43
【问题描述】:
我想知道如何通过付款部分将外键添加到我的网站中,我创建了一个列表研讨会供用户首先选择,包括一个时间表。之后,用户可以点击注册并将页面重定向到包含信用卡或现金的付款详细信息表单。用户付款并单击确认按钮后,数据库应增加一,包括 id 的主键(自动生成)。
我的问题是为什么我仍然得到一个 -1 而不是 +1 的 id(我检查过,数据库没有在 SQL Server 中更新),因为 id 是 -1。
这是我关于支付部分的代码
if (tbxName.Text != null && tbxCC.Text != null && ddlCCType.Text != null && tbxExpDate.Text != null)
{
ShoppingCart sc = (ShoppingCart)Session["cart"];
sc.Name = tbxName.Text;
if (rdbCash.Checked == true)
{
sc.OptionPay = rdbCash.Text;
}
else
{
sc.OptionPay = rdbCC.Text;
}
sc.CreditCard = tbxCC.Text;
sc.CreditCardType = ddlCCType.Text;
sc.SecurityCode = tbxCode.Text;
sc.CCExpiryDate = tbxExpDate.Text;
//sc.Registration.RegId = sc.Id;
int id = ShoppingCartDBMgr.purchaseSeminar(sc);
lblOutput.Text = "Confirm. order id is " + id;
//display output for payment successfully
//lblOutput.Text = "Payment Successfully!";
//make it null for amount, date and session of cart after transaction are being successful
lblAmount.Text = null;
lblDate.Text = null;
Session["cart"] = null;
我的支付数据库管理器代码:
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();
}
}
【问题讨论】:
-
因为从不执行插入,所以只执行“set identity_insert...”
标签: c# asp.net sql-server visual-studio