为什么更新对象只能工作之一,具体做法? [英] Why does updating an object only work one, particular way?

查看:94
本文介绍了为什么更新对象只能工作之一,具体做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用更新的EF4对象。一个目的是从强类型页传递到操作方法和

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?

推荐答案

在你的行动方法的情况下,你有型方案的两个不同的对象。场景指向对象和updateScenario点到另一个中的一个。随着code线:

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

所有你做的是造成updateScenario指向同一个对象该方案指向,你是不是抄袭构成从一个到另一个对象的值。从本质上讲,你的数据库上下文是知道的只是方案的2实例1。方案的另一个实例是在上下文之外创建的背景下尚未作出意识到这一点。

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().

心连心

这篇关于为什么更新对象只能工作之一,具体做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆