Can't SaveChanges with Entity Framework in ASP.Net MVC 3 project

筅森魡賤 提交于 2019-12-04 07:51:36

You need to attach the entity instance created outside EF and let EF know that it has been modified.

public void SaveProduct(Product product)
{
    if (product.ProductID == 0)
    {
        context.Products.Add(product);
    }
    else
    {
        context.Products.Attach(product);
        context.Entry(product).State = EntityState.Modified;
    }

    context.SaveChanges();
}

You should Attach the Product instances to the context before SaveChanges

public void SaveProduct(Product product)
{
    if (product.ProductID == 0)
        context.Products.Add(product);
    else
    {    
        context.Products.Attach(product);
        context.Entry(product).State = EntityState.Modified;
    }
    context.SaveChanges();
}

Indeed, you should attach.

Say you call Edit(1). Your controller will load a Product with ID = 1 from your DB and generate an HTML view based upon its properties (the ones you've declared in your view anyway). As soon as you leave the Edit(int productId) method and you see your view appear in your browser, your DbContext has lost the Product with that ID; it has gone out of scope. If you then make changes to your Product and submit your form, ASP MVC will cobble together a new Product object based upon your form fields (among other things) and pass that object to the Edit(Product product) method. Since this is a completely new Product object and the old Product object went out of scope anyway, you DbContext has no idea how the new Product relates to your DB: is it a new object, is it an existing object, if it exists does it have any changes? If you attach the Product object and set its state to modified, then the DbContext can start checking which properties have changed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!