Why does updating an object only work one, particular way?

谁说胖子不能爱 提交于 2019-12-11 06:38:39

问题


I am trying to update an object using EF4. An object is passed from the strongly-typed page to the action method and

[HttpPost]
public ActionResult Index(Scenario scenario, Person person)
{
    // Some business logic.

    // Update Scenario with Person information.
    scenario.Person = person;

    // Update the corresponding object and persist the changes.
    // Note that the repository stems from the repository pattern. Contains the ObjectContext.
    Scenario updateScenario = repository.GetScenario(scenario.ScenarioID);
    updateScenario = scenario;

    repository.Save();
}

However, the problem is that the changes do not persist when I do this. However, if I instead update every single property within the scenario individually and then persist the changes (via the Save method), everything is persisted.

I'm confused why this is happening. In my real application, there are MANY items and subobjects within a Scenario so it is not feasible to update every individual property. Can someone please help clear up what is happening and what I need to do to fix it?


回答1:


In the context of your action method, you have two different objects of type Scenario. scenario points to one of the objects and updateScenario points to another one. With the line of code:

updateScenario = scenario

All you are doing is causing the updateScenario to point to the same object that scenario points to, you are not copying the values that make up the object from one to another. Essentially, your database context is aware of only 1 of the 2 instances of Scenario. The other instance of Scenario was created outside of the context and the context has not been made aware of it.

In your particular scenario you can accomplish what you want by not taking a Scenario on your parameter, and instead, pull the Scenario that you want to update from your database context and in your action method, invoke:

this.TryUpdateModel(updateScenario);

This will cause the model binder to update the property/fields on the Scenario object that your database context is aware of, and therefore will persist the changes when you call Save().

HTH



来源:https://stackoverflow.com/questions/4731348/why-does-updating-an-object-only-work-one-particular-way

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