【问题标题】:How I can update inventory stock after purchase - asp.net webapplication购买后如何更新库存 - asp.net web application
【发布时间】:2021-10-10 23:08:15
【问题描述】:

有人可以帮助我吗?购买后我无法更新库存记录,它显示空错误。我无法从数据库中检索原始数据。
这是我的代码:

DBContext db = new DBContext(); 
var inTB = db.InventoryTBs.Where(s => s.id == customerTB.CustomerID).FirstOrDefault(); 
inTB.Quantity += customerTB.CQuantity; 
db.InventoryTBs.Add(inTB); 
db.SaveChanges();

谢谢

【问题讨论】:

    标签: c# asp.net-mvc entity-framework inventory-management


    【解决方案1】:

    要修改上下文获取的现有记录,只需调用SaveChanges()

    var inTB = db.InventoryTBs.Where(s => s.id == customerTB.CustomerID).FirstOrDefault(); 
    if (inTB  != null)
    {
        // Modifying existing record
        inTB.Quantity += customerTB.CQuantity;    
    }
    else
    {   
        // Adding a new record
        db.InventoryTBs.Add(new InventoryTB() { Quantity = customerTB.CQuantity; /* set another properties */});
    }
    db.SaveChanges();
    

    在您的情况下,customerTB.CustomerID 的记录不存在。因此,可能需要新建一个,然后将其添加到InventoryTBs

    更多信息请见:Modifying data via the DbContext

    【讨论】:

    • 感谢您的帮助。这就是我一直在寻找的答案。效果很好,再次感谢。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2022-01-11
    • 2023-03-13
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多