我正在使用购物车,并且在使用Find()方法时遇到了MissingPrimaryKeyException(表没有主键),当我已经将主键设置为数据表时,我感到困惑。< / p>
我的创建购物车代码并添加到购物车:
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;
}
答案 0 :(得分:1)
您已使用<ProductID>
将列添加为主键,而列名称只是ProductID
。奇怪的是,这种语法没有错误(至少用LinqPAD测试你的代码)但是如果你尝试在添加后打印PrimaryKey,你会发现没有定义PrimaryKey。
所以,这段代码
DataColumn[] primaryKeys = new DataColumn[1];
primaryKeys[0] = shoppingCartDataTable.Columns["<ProductID>"];
shoppingCartDataTable.PrimaryKey = primaryKeys;
foreach(DataColumn dc in shoppingCartDataTable.PrimaryKey)
Console.WriteLine(dc.ColumnName);
不会产生任何输出
修复只需添加PrimaryKey和
DataColumn[] primaryKeys = new DataColumn[1];
primaryKeys[0] = shoppingCartDataTable.Columns["ProductID"];
shoppingCartDataTable.PrimaryKey = primaryKeys;
foreach(DataColumn dc in shoppingCartDataTable.PrimaryKey)
Console.WriteLine(dc.ColumnName);
打印ColumnName
答案 1 :(得分:0)
我一直在搞清楚,发现我犯了一个大错,我还没有调出CreateShopCart方法,这就是AddShopCartItem方法在表中没有主键的原因。
干杯并感谢您的帮助。