我有以下代码来更新一些库存值...
private static void UpdateInventory(int prodId, int qty)
{
using (var context = new uStore7_1Entities())
{
//Get the catalogNo and ProductUnitID of the product passed in so we can find all identical products that might just be boxed differently
var currProdItem = context.Products.Where(c => c.ProductID.Equals(prodId))
.Select(c => new {c.CatalogNo, c.ProductUnitID}).FirstOrDefault();
//Get the units per box factor for calculating total product ordered
var prodIdAmount =
context.ProductUnits.Where(pa => pa.ProductUnitID.Equals(currProdItem.ProductUnitID))
.Select(pa => pa.Amount)
.FirstOrDefault();
//Calculate the total number of units for this item
var prodUnits = qty*prodIdAmount;
//Get the entire list of products with the specified catalog number excluding the product passed in
var uStoreProducts =
context.Products.Where(p => p.CatalogNo.Equals(currProdItem.CatalogNo) && !p.ProductID.Equals(prodId))
.Select(p => p.ProductID);
//Loop through each product in the uStoreProductsList
foreach (var uStoreProduct in uStoreProducts)
{
var currentProduct = uStoreProduct;
//Get the current product's ProductUnitId to get the 'pieces' per "box"
var currentUnitId =
context.Products.Where(u => u.ProductID.Equals(currentProduct))
.Select(u => u.ProductUnitID)
.FirstOrDefault();
//Use the ProductUnitId to get the "Amount" from the ProductUnits table.
var inventoryFactor =
context.ProductUnits.Where(i => i.ProductUnitID.Equals(currentUnitId))
.Select(i => i.Amount)
.FirstOrDefault();
//Divide the quantity passed
var qtyInUnits = prodUnits/inventoryFactor;
var inventory =
context.ProductInventories.Where(pi => pi.ProductID.Equals(currentProduct))
.Select(pi => pi.InventoryQuantity)
.FirstOrDefault();
/*var inventory = (from i in context.ProductInventories
where i.ProductID == currentProduct
select i).FirstOrDefault();
*/
if (inventory != null)
{
var newinv = inventory - qtyInUnits;
inventory = newinv;
//context.SaveChanges();
}
}
context.SaveChanges();
}
}
SaveChanges()
似乎没有更新任何内容。我调试了它,库存值变为所需的值,但由于某种原因它没有更新。我已经在循环内部和循环外部尝试过,两者都没有变化。有任何想法吗?我在这里缺少什么?
答案 0 :(得分:2)
您的code
不会更新任何内容。您所做的只是收集实体并在局部变量中分配计算值。但是,您实际上从未更改过property
。{/ p>之一的entities
请注意,选择实体的属性,将它们存储在变量中并替换此变量的值不起作用。如果要修改实体,则需要选择实体。
答案 1 :(得分:2)
您的问题是对象替换,而不是重新分配。创建“newinv”时,它与您的上下文分离,而“inventory”是附加对象。当“newinv”被分配给“库存”时,它就会失去与上下文的关联。
试试这个:
var prodInventory =
context.ProductInventories
.Where(pi => pi.ProductID.Equals(currentProduct))
.FirstOrDefault();
if (prodInventory != null)
{
var newinv = prodInventory.InventoryQuantity - qtyInUnits;
prodInventory.InventoryQuantity = newinv; // This updates the actual context object now.
}