【发布时间】:2012-03-24 08:55:49
【问题描述】:
我正在尝试使用 DBContext 的 ChangeTracker 对象实现 AuditLog,我遇到了一个问题,DbEntityEntry.OriginalValues 被清除并替换为DbEntityEntry.CurrentValues。我注意到问题是如何我正在更新 DbContext 中正在跟踪的对象(原始帖子:Entity Framework DbContext SaveChanges() OriginalValue Incorrect)。
所以现在我需要一些帮助,以正确方法使用 MVC 3 中的存储库模式和实体框架 4 更新持久对象。此示例代码改编自 Pro Asp.NET MVC 3 Framework 书中的 SportsStore 应用程序由 Apress 发布。
这是我在 AdminController 中的“编辑”发布操作:
[HttpPost]
public ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
// Here is the line of code of interest...
repository.SaveProduct(product, User.Identity.Name);
TempData["message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(product);
}
}
这将调用具体类 EFProductRepository(实现 IProductRepository 接口并通过 Ninject 注入)。这是具体存储库类中的SaveProduct 方法:
public void SaveProduct(Product product, string userID)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
else
{
context.Entry(product).State = EntityState.Modified;
}
context.SaveChanges(userID);
}
问题(正如我在之前的 SO 帖子中引起我注意的那样)是,当 context.Entry(product).State = EntityState.Modified; 被调用时,它会以某种方式破坏 ChangeTracker 报告更改的能力。所以在我重载的 DBContext.SaveChanges(string userID) 方法中,我在 ChangeTracker.Entries().Where(p => p.State == System.Data.EntityState.Modified).OriginalValues 对象中看不到准确的值。
如果我将我的 EFProductRepository.SaveProduct 方法更新为此它可以工作:
public void SaveProduct(Product product, string userID)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
else
{
Product prodToUpdate = context.Products
.Where(p => p.ProductID == product.ProductID).FirstOrDefault();
if (prodToUpdate != null)
{
// Just updating one property to demonstrate....
prodToUpdate.Name = product.Name;
}
}
context.SaveChanges(userID);
}
我想知道更新 Product 对象的正确方法,并将其保存在这种情况下,以便 ChangeTracker 准确跟踪我对存储库中 POCO 类的更改。我应该做后一个例子(当然除了复制所有可能已经更新的字段),还是应该采取不同的方法?
在本例中,“Product”类非常简单,只有字符串属性和小数属性。在我们的实际应用程序中,我们将拥有“复杂”类型,并且 POCO 类将引用其他对象(即具有地址列表的人)。我知道我可能还需要做一些特别的事情来跟踪这种情况下的变化。也许了解这一点会改变我在这里收到的一些建议。
【问题讨论】:
标签: c# asp.net-mvc-3 entity-framework