//[DataObjectMethod(DataObjectMethodType.Insert,false)] it is only for view, e.g: listview.... public void AddToCart(string currentUserName, int stockItemID, int quantity) { using (eToolContext context = new eToolContext()) { var currentCustomer = context.OnlineCustomers.FirstOrDefault( x => x.UserName == currentUserName); if (currentCustomer == null) { OnlineCustomer newCustomer = new OnlineCustomer(); newCustomer.UserName = currentUserName; newCustomer.CreatedOn = DateTime.Now; // Or //OnlineCustomer currentCustomer = new OnlineCustomer() //{ // UserName = user.Identity.Name, // CreatedOn = DateTime.Now //}; currentCustomer = context.OnlineCustomers.Add(newCustomer); context.SaveChanges(); } var currentShoppingCart = context.ShoppingCarts.FirstOrDefault( x => x.OnlineCustomer.UserName == currentUserName); if (currentShoppingCart == null) { ShoppingCart newShoppingCart = new ShoppingCart() { OnlineCustomerID = currentCustomer.OnlineCustomerID, CreatedOn = DateTime.Now }; currentShoppingCart = context.ShoppingCarts.Add(newShoppingCart); context.SaveChanges(); } ShoppingCartItem currentCartItem = new ShoppingCartItem() { ShoppingCartID = currentShoppingCart.ShoppingCartID, StockItemID = stockItemID, Quantity = quantity }; foreach (ShoppingCartItem cartItem in context.ShoppingCartItems) { if(cartItem.ShoppingCartID == currentShoppingCart.ShoppingCartID && cartItem.StockItemID == stockItemID) { context.Entry<ShoppingCartItem>(context.ShoppingCartItems.Attach(currentCartItem)).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } else if(cartItem.ShoppingCartID == currentShoppingCart.ShoppingCartID && cartItem.StockItemID != stockItemID) { //context.ShoppingCartItems.Add(currentCartItem); currentCartItem = context.ShoppingCartItems.Add(currentCartItem); } } //??? should be another way to update var currentStockItem = from skItem in context.StockItems where skItem.StockItemID == stockItemID select new StockItem { StockItemID = skItem.StockItemID, Description = skItem.Description, SellingPrice = skItem.PurchasePrice, PurchasePrice = skItem.PurchasePrice, QuantityOnHand = skItem.QuantityOnHand - quantity, QuantityOnOrder = skItem.QuantityOnOrder,//??? is this for customer or for vendor ReOrderLevel = skItem.ReOrderLevel, Discontinued = skItem.Discontinued, VendorID = skItem.VendorID, VendorStockNumber = skItem.VendorStockNumber, CategoryID = skItem.CategoryID }; context.Entry<StockItem>(context.StockItems.Attach((StockItem)currentStockItem)).State = System.Data.Entity.EntityState.Modified; context.SaveChanges(); } }
public void AddToOnlineCustomer(Guid TrC ,string Name) { using(var context = new eToolDBContext()) { var Customer = context.OnlineCustomers.SingleOrDefault(x => x.TrackingCookie == TrC ); if (Customer == null) { Customer = new OnlineCustomer { //OnlineCustomerID = ID, UserName = Name, CreatedOn = DateTime.Now, }; context.OnlineCustomers.Add(Customer); context.SaveChanges(); } } }