====== 微软数据访问教程中有关业务逻辑执行的问题 ======

愚者只看星不看答案 2019-05-28 10:40:47
原文(实际是翻译后转载的)链接

https://www.jb51.net/article/83252.htm

文章比较长,业务规则是:

如果一个供应商仅仅供应一个产品的话,那么修改产品的信息的时候,是不能将这个产品的状态设置为停用.

不用太纠结是哪种语言,也不用太纠结细节。。。

代码如下:


public bool UpdateProduct(string productName, int? supplierID, int? categoryID, string quantityPerUnit,
decimal? unitPrice, short? unitsInStock, short? unitsOnOrder, short? reorderLevel,
bool discontinued, int productID)
{
Northwind.ProductsDataTable products = Adapter.GetProductByProductID(productID);
if (products.Count == 0)
// 根据productID查找时,没有找到匹配项,返回false
return false;


// product 即表示 Product 表中的一条记录
Northwind.ProductsRow product = products[0];

// 业务规则检查 – 不能停用某供应商所提供的唯一一个产品
if (discontinued)
{
// 获取我们从这个供应商处获得的所有产品
Northwind.ProductsDataTable productsBySupplier = Adapter.GetProductsBySupplierID(product.SupplierID);

if (productsBySupplier.Count == 1)
// 这是我们从这个供应商处获得的唯一一个产品,如果仅仅供应 1 个产品,则抛出异常
throw new ApplicationException("You cannot mark a product as discontinued if its the only product purchased from a supplier");
}

product.ProductName = productName;
if (supplierID == null) product.SetSupplierIDNull(); else product.SupplierID = supplierID.Value;
if (categoryID == null) product.SetCategoryIDNull(); else product.CategoryID = categoryID.Value;
if (quantityPerUnit == null) product.SetQuantityPerUnitNull(); else product.QuantityPerUnit = quantityPerUnit;
if (unitPrice == null) product.SetUnitPriceNull(); else product.UnitPrice = unitPrice.Value;
if (unitsInStock == null) product.SetUnitsInStockNull(); else product.UnitsInStock = unitsInStock.Value;
if (unitsOnOrder == null) product.SetUnitsOnOrderNull(); else product.UnitsOnOrder = unitsOnOrder.Value;
if (reorderLevel == null) product.SetReorderLevelNull(); else product.ReorderLevel = reorderLevel.Value;
product.Discontinued = discontinued;

// 更新产品记录
int rowsAffected = Adapter.Update(product);

// 如果刚好更新了一条记录,则返回true,否则返回false
return rowsAffected == 1;
}


这里的问题是当执行 if (productsBySupplier.Count == 1) 时,此供应商供应了 2 个产品。继续执行 product.ProductName = productName; 时,

在另一个CPU核心上,或是单核发生线程切换时,另一个用户删除了该供应商的一个产品的代码被完整的执行了。此时该供应商供应的产品数量为 1,

那么接下来的逻辑将继续执行,但是这个供应商仅仅供应 1个产品了,却执行了 停用 ,也就违反了业务规则 。

第一个问题,是不是将业务逻辑放到存储过程里来解决而不是应用层来解决更好

第二个问题,如果根本上解决这个问题?

多谢。
...全文
101 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
stherix 2019-05-29
  • 打赏
  • 举报
回复
代码没有什么问题啊 只是这种可能会冲突的地方,数据库可以加锁
耗子哭死猫 2019-05-29
  • 打赏
  • 举报
回复
数据库产品的信息表要有一个状态,当别人修改的时候false,标记是哪个用户设置的。 修改完更新回状态。 也可以数据库加锁,你修改的时候,别人进不去。
  • 打赏
  • 举报
回复
@stherix 请细说下。。。多谢。

111,095

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧