实体框架savechanges()不工作EF5, . net 4
本文关键字:EF5 net 工作 框架 savechanges 实体 | 更新日期: 2023-09-27 18:08:20
我有以下代码来更新一些库存值…
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()
似乎没有更新任何东西。我已经调试了它,库存值被更改为所需的值,但由于某种原因,它没有更新。我在循环内和循环外都试过了,都没有变化。什么好主意吗?我遗漏了什么?
您的问题是对象替换,而不是重新赋值。当"newinv"被创建时,它与上下文是分离的,而"inventory"是附加对象。当"newinv"被赋值给"inventory"时,它就失去了与上下文的关联。
试试这个:
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.
}
您的code
没有更新任何内容。您所要做的就是收集实体并在局部变量中分配计算值。但是你从来没有真正改变过你的entities
中的一个property
。
请注意,选择实体的属性,将它们存储在变量中并替换该变量的值是不起作用的。如果要修改实体,需要选择该实体