【发布时间】:2011-05-31 00:33:05
【问题描述】:
这是我的控制器代码:
[HttpPost]
public ActionResult Edit(ProductViewModel viewModel)
{
Product product = _ProductsRepository.GetProduct(viewModel.ProductId);
TryUpdateModel(product);
if (ModelState.IsValid)
{
_productsRepository.SaveProduct(product);
TempData["message"] = product.Name + " has been saved.";
return RedirectToAction("Index");
}
return View(viewModel); // validation error, so redisplay same view
}
[HttpPost]
public ActionResult Create(CommodityCategoryViewModel viewModel)
{
Product product = new Product();
TryUpdateModel(product);
if (ModelState.IsValid)
{
_productsRepository.SaveProduct(product);
TempData["message"] = product.Name + " has been saved.";
return RedirectToAction("Index");
}
return View(viewModel); // validation error, so redisplay same view
}
它们都调用了一个 Save() 函数,在这里定义:
public class ProductsRepository
{
private readonly MyDBEntities _entities;
public ProductsRepository()
{
_entities = new MyDBEntities();
}
public void SaveProduct(Product product)
{
// If it's a new product, just attach it to the DataContext
if (product.ProductID == 0)
_entities.Products.Context.AddObject("Products", product);
else if (product.EntityState == EntityState.Detached)
{
// We're updating an existing product, but it's not attached to this data context, so attach it and detect the changes
_entities.Products.Context.Attach(product);
_entities.Products.Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, product);
}
_entities.Products.Context.SaveChanges(); // Edit function hits here
}
}
当我调用 Create 时,它会在 SaveProduct() 函数中点击 AddObject(),并正确保存产品。
当我调用 Edit 时,它只点击 SaveProduct() 函数中的 _entities.Products.Context.SaveChanges(),并且产品没有被保存。
我做错了什么?
【问题讨论】:
-
为什么不使用 _entities.SaveChanges();反而?你最好使用这种模式: using(var context = new MyDBEntities()){...} 进行数据访问。
-
您的产品对象可能未处于修改状态,因为您的视图模型(ProductViewModel)与您的实体(产品)不同。尝试检查更改的实体
context.ChangeTracker.Entries() -
@Eranga - EntityState 已修改。我需要对我的代码进行哪些更改?
-
MyDBEntities 是继承自 DbContext 还是 ObjectContext?尝试
_entities.SaveChanges()检查您是否没有为GetProduct和SaveProduct使用相同的上下文:) -
产品保存在与保存产品相同的上下文中吗?如何检查产品没有保存?
标签: c# asp.net entity-framework