在删除带有Items的订单后,如何将数量和消费字段恢复到Item表中的原始数字

本文关键字:恢复 字段 Item 数字 原始 Items 删除 | 更新日期: 2023-09-27 18:11:58

我试图恢复我的QuantityConsumption字段到他们原来的数字之前,我添加Items到我的Order在我的 Item。因此,在我删除Order之后,Item应该在我添加这些项目之前返回其默认的QuantityConsumption

问题是我的OrderItem表通过OrderItem表链接。所以,OrderDelete Post Method中的code不会那么简单。然而,当我从Order中单独删除OrderItems时,我试图以同样的方式做到这一点。

这是我尝试过的,但它不起作用,字段没有发生任何变化,它们只是保持不变。什么好主意吗?如果你需要任何额外的代码,请让我知道。

Delete POST method in ORDER:

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
{           
 Order order = db.Orders.Find(id);
            var query = from ord in db.OrderItems where ord.OrderItemID == id select ord; // supposed to get the orderitem based on the OrderID
            foreach (OrderItem ord in query)
            {
                var item = from o in db.Items where o.ItemID == orderItem.ItemID select ord; // supposed to get the item linked to that specific orderitem
                foreach (Item o in item)
                {
                    o.Consumption = o.Consumption - orderItem.Quantity; //restores the consumption (aka how much stock was used)
                    o.Quantity = o.Quantity + orderItem.Quantity; //restores the quantity by adding back items that were taken out
                }
            }
            db.Orders.Remove(order);
            db.SaveChanges();
            return RedirectToAction("Index");
}

在删除带有Items的订单后,如何将数量和消费字段恢复到Item表中的原始数字

总结在评论/聊天中发现的打字错误:

因为你已经建立了关系,我们可以使用它们来获得相关的实体,而不是每次都从db上下文中选择。

// note addition of ToList()
var query = (from ord in order.OrderItems select ord).ToList();

和在第一个foreach内:

var item = from o in db.Items select o;