c# - 我可以创建实体,但无法编辑实体

标签 c# asp.net entity-framework

这是我的 Controller 代码:

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

我做错了什么?

最佳答案

取而代之的是:

// 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 是一个猜测....无论您的 key 是什么。

关于c# - 我可以创建实体,但无法编辑实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6181860/

相关文章:

c# - 下载文件 C#

c# - AutoMapper - 映射子列表时非常奇怪的行为

c# - 未设置对象引用 c#

c# - 在 WMI 对象上调用方法时出现 InvalidOperationException

c# - 使用 HTML 或 C# 更改 GridView 中的列名称

asp.net - 如何查看一个网站有多少人在线

C# - Entity Framework - 连接方法

c# - Entity Framework 映射奇怪 - 成员名称不能与其封闭类型相同

c# - 有没有一种简单的方法可以替换 Azure 云服务引用 dll,而无需重新发布服务?

c# - ASP.NET 托管 Active Directory RSAT powershell 脚本--DC 挂断