我正在处理购物车,并且在使用 Find() 方法时得到了这个 MissingPrimaryKeyException(表没有主键),当我已经为数据表设置了主键时,我很困惑出了什么问题。
我的创建购物车并添加到购物车的代码:
public static void CreateShopCart()
{
// create a Data Table object to store shopping cart data
DataTable shoppingCartDataTable = new DataTable("Cart");
shoppingCartDataTable.Columns.Add("ProductID", typeof(int));
// make ProductID primary key
DataColumn[] primaryKeys = new DataColumn[1];
primaryKeys[0] = shoppingCartDataTable.Columns[0];
shoppingCartDataTable.PrimaryKey = primaryKeys;
shoppingCartDataTable.Columns.Add("Quantity", typeof(int));
shoppingCartDataTable.Columns.Add("UnitPrice", typeof(decimal));
shoppingCartDataTable.Columns.Add("ProductName", typeof(string));
shoppingCartDataTable.Columns.Add("ProductDescription", typeof(string));
shoppingCartDataTable.Columns.Add("SellerUsername", typeof(string));
shoppingCartDataTable.Columns.Add("Picture", typeof(string));
// store Data Table in Session
HttpContext.Current.Session["Cart"] = shoppingCartDataTable;
}
public static void AddShopCartItem(int ProductID, decimal Price, string strPName, string strPDesc, string strSellerUsername, string strImage)
{
int intQty = 1;
var retStatus = HttpContext.Current.Session["Cart"];
if (retStatus == null)
CreateShopCart();
// get shopping data from Session
DataTable shoppingCartDataTable = (DataTable)HttpContext.Current.Session["Cart"];
// Find if ProductID already exists in Shopping Cart
DataRow dr1 = shoppingCartDataTable.Rows.Find(ProductID); **<- This is the line giving the error**
if (dr1 != null)
{
// ProductID exists. Add quantity to cart
intQty = (int)dr1["Quantity"];
intQty += 1; // increment 1 unit to be ordered
dr1["Quantity"] = intQty; // store back into session
}
else
{
// ProductID does not exist; create a new record
DataRow dr = shoppingCartDataTable.NewRow();
dr["ProductID"] = ProductID;
dr["ProductName"] = strPName;
dr["ProductDescription"] = strPDesc;
dr["Quantity"] = intQty;
dr["UnitPrice"] = Price;
dr["SellerUsername"] = strSellerUsername;
dr["Picture"] = strImage;
shoppingCartDataTable.Rows.Add(dr);
}
// store back shopping cart in session
HttpContext.Current.Session["Cart"] = shoppingCartDataTable;
}