开发者

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

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 m开发者_StackOverflow社区ethod), 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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜