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 Cart object. /// </summary> /// <param name="id">Initial value of the Id property.</param> /// <param name="userName">Initial value of the UserName property.</param> public static Cart CreateCart(global::System.Int32 id, global::System.String userName) { Cart cart = new Cart(); cart.Id = id; cart.UserName = userName; return cart; }
/// <summary> /// Deprecated Method for adding a new object to the Carts EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// </summary> public void AddToCarts(Cart cart) { base.AddObject("Carts", cart); }