protected void AddToCartButton_Click(object sender, EventArgs e) { using (ToyStoreEntities context = new ToyStoreEntities()) { String CurrentUserName = ((Site1)Page.Master).CurrentUserName; Cart myCart; //找到该用户的购物车 var query = from p in context.Carts where p.UserName == CurrentUserName select p; if (query.Count() == 0) { myCart = new Cart(); myCart.UserName = CurrentUserName; context.AddToCarts(myCart); } else { myCart = query.First(); } //查找是否已有该购物车明细 var query1 = from p in myCart.CartDetails where p.Product.Id == CurrentProduct.Id select p; CartDetail myCartDetail; if (query1.Count() == 0) { //如果没有,新增 myCartDetail = new CartDetail(); myCartDetail.Cart = myCart; myCartDetail.ProductId = CurrentProduct.Id; myCartDetail.OTY = 1; } else { //如果有,修改数量 myCartDetail = query1.First(); myCartDetail.OTY += 1; } context.SaveChanges(); } }
/// <summary> /// Create a new CartDetail object. /// </summary> /// <param name="id">Initial value of the ID property.</param> /// <param name="oTY">Initial value of the OTY property.</param> /// <param name="cartId">Initial value of the CartId property.</param> /// <param name="productId">Initial value of the ProductId property.</param> public static CartDetail CreateCartDetail(global::System.Int32 id, global::System.Int32 oTY, global::System.Int32 cartId, global::System.Int32 productId) { CartDetail cartDetail = new CartDetail(); cartDetail.ID = id; cartDetail.OTY = oTY; cartDetail.CartId = cartId; cartDetail.ProductId = productId; return cartDetail; }
/// <summary> /// Deprecated Method for adding a new object to the CartDetails EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// </summary> public void AddToCartDetails(CartDetail cartDetail) { base.AddObject("CartDetails", cartDetail); }