protected void AddToCartButton_Click(object sender, EventArgs e) { using (LiBoClothesShopEntities context = new LiBoClothesShopEntities()) { String CurrentUserName = ((Site1)Page.Master).CurrentUserName; int colorId = Convert.ToInt32(DropDownListColor.SelectedItem.Value); int sizeId = Convert.ToInt32(DropDownListSize.SelectedValue); //查找用户是否有购物车 var query = from cart in context.CartInfoes where cart.UserName == CurrentUserName select cart; CartInfo myCart; if (query.Count() == 0) { myCart = new CartInfo() { UserName = CurrentUserName, TotalPrice = 0 }; context.AddToCartInfoes(myCart); context.SaveChanges(); } else { myCart = query.FirstOrDefault(); } //查找是否已有该购物车明细 var query1 = from p in context.CartDetails where p.CartInfo.UserName == CurrentUserName && p.ColorId == colorId && p.SizeId == sizeId && p.ClothId == CurrentProduct.Id select p; CartDetail myCartDetail; if (query1.Count() == 0) { //如果没有,新增 myCartDetail = new CartDetail(); myCartDetail.CartId = myCart.ID; myCartDetail.SizeId = sizeId; myCartDetail.ColorId = colorId; myCartDetail.ClothId = CurrentProduct.Id; myCartDetail.QTY = 1; context.AddToCartDetails(myCartDetail); } else { //如果有,修改数量 myCartDetail = query1.First(); myCartDetail.QTY += 1; } //修改总价 myCart.TotalPrice += CurrentProduct.Price; context.SaveChanges(); } }