//增加庫存量 public void IncStock(XINEntities _context, string ProductID, int Quantity) { if (ProductID == null) { Exception ex = new Exception("計算庫存量的資料不可以含有空值!"); ex.Source = "null"; throw ex; } //定義影響的資料列數 int rowsAffected; //更新庫存量 rowsAffected = _context.ExecuteStoreCommand( "UPDATE Product SET Stock = Stock + {0} " + "WHERE ProductID = {1} ", Quantity, ProductID); //檢查影響的資料列數 if (rowsAffected == 0) { //修改失敗,舉發例外 Exception ex = new Exception("計算庫存量發生不可預期的錯誤!"); ex.Source = "Quantity"; throw ex; } }
//減少庫存量 public void DecStock(XINEntities _context, string ProductID, int Quantity) { if (ProductID == null) { Exception ex = new Exception("計算庫存量的資料不可以含有空值!"); ex.Source = "null"; throw ex; } //重讀ObjectContext的庫存記錄 _context.Refresh(RefreshMode.StoreWins, _context.Product); //查詢指定品項的庫存量 var qryStock = (from P in _context.Product where P.ProductID == ProductID select P.Stock).FirstOrDefault(); int CurrQty = (int)qryStock; if ((CurrQty - Quantity) < 0) { Exception ex = new Exception(string.Format( "商品編號{0}的庫存量不足,無法出貨!", ProductID)); ex.Source = "Stock"; throw ex; } //定義影響的資料列數 int rowsAffected; //更新庫存量 rowsAffected = _context.ExecuteStoreCommand( "UPDATE Product SET Stock = Stock - {0} " + "WHERE ProductID = {1} ", Quantity, ProductID); //檢查影響的資料列數 if (rowsAffected == 0) { //修改失敗,舉發例外 Exception ex = new Exception("計算庫存量發生不可預期的錯誤!"); ex.Source = "Quantity"; throw ex; } }