Strongly-Typed ASP.NET MVC with Entity Framework

后端 未结 5 536
孤街浪徒
孤街浪徒 2020-12-16 09:01

This code fails to actually save any changes:

//
// POST: /SomeType/Edit/5

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, SomeType Model)
{         


        
5条回答
  •  庸人自扰
    2020-12-16 09:35

    You need to get the ObjectStateManager from your ObjectContext. With the ObjectStateManager, you can explicitly set the state for your object without needing to make a call to the database:

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(Guid id, SomeType Model)
    {
        db.AttachTo(Model.GetType().Name, Model);
    
        ObjectStateManager stateMgr = db.ObjectStateManager;
        ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model);
        stateEntry.SetModified(); // Make sure the entity is marked as modified
        //db.ApplyPropertyChanges(Model.EntityKey.EntitySetName, Model);
    
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    

    The ObjectStateEntry also allows you to apply finer-grained state change data via the SetModifiedProperty. If you call SetModified, EF will treat the entire entity as modified, and persist every property to the data store. With SetModifiedProperty, EF can optimize the queries and only involve the properties that have actually changed. Using SetModifiedProperty is obviously more complex, as you usually need to know the original value of each property.

    I hope this helps. ObjectStateManager is a powerful little tool in the EF toolbox, and can help improve EF v1.0's otherwise morbid performance and efficiency.

提交回复
热议问题