我可以创建一个实体,但我无法编辑实体

时间:2011-05-31 00:33:05

标签: c# asp.net entity-framework

这是我的控制器代码:

[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(),并且不会保存产品。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

而不是:

// 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);     

尝试:

Product origProduct =_entities.Products.Where(m=>m.ProductId == product.ProductId).Single();
_entities.Products.Attach(product, origProduct);

这将加载附加的原始对象并为其提供新值。 ProductId是一个猜测....它将是你的钥匙。