如何使用ObjectContext执行更新

时间:2011-01-07 20:32:56

标签: database asp.net-mvc-2 entity-framework-4

我在ASP.NET MVC 2 Web应用程序中使用EF4。我试图将数据保存到数据库。将添加新数据添加到数据库是相当简单的。我这样做是这样的:

PeopleEntities entities = ObjectContextFactory.GetPeopleEntities();
entities.People.AddObject(person); // The Person object created from user input.
entities.SaveChanges();

但是,这会产生令人遗憾的副作用,即始终将新对象保存到我的数据库中。我确实需要这个功能(当然),但我也想要更新数据库中的现有项目(或者,如果数据库中尚不存在该项目,则保存为新项目。)

我尝试用以下内容替换上面的第二行:

entities.People.ApplyCurrentValues(person);

但我收到此InvalidOperationException:

  

具有与之匹配的键的对象   提供的对象的键不能   可以在ObjectStateManager中找到。   验证密钥的值   提供的对象匹配键值   必须进行更改的对象   应用

无论我是尝试添加新人,还是尝试编辑某人,都会发生这种情况。我该怎么做才能解决这个问题?

更新问题:

我尝试了下面提供的答案,但是当我去调试Single语句时,我发现我保存的Person的ID始终为0 - 即使我从数据库中检索到它。所以,我想发布我正在做的事情,以便首先检索Web应用程序。也许这会有所帮助。

当我导航到显示Person信息的页面时,地址为:

http://localhost/Person/Index/1

其中1是数据库中Person的ID。我通过包含以下行的存储库方法检索Person(实体是存储库类的成员变量):

public Person GetPerson(int id)
{
    return entities.People.FirstOrDefault(p => p.PersonID == id);
}

从我项目的控制器调用此方法。看起来像这样:

public ActionResult Index(int id)
{
    var entities = ObjectContextFactory.GetScenarioDBEntities();
    Person person = new PersonRepository(entities).GetPerson(id);
    return View("Index", person);
}

现在我正在考虑这个问题,我想知道每次想要检索新Person时是否错误地实例化本地实体对象。 (现在去研究。)无论如何,当我这样做时,最终去保存前一个Person,我发现PersonID值总是== 0。

3 个答案:

答案 0 :(得分:4)

只要您从同一个确切的上下文中检索对象,

entities.SaveChanges();就是您所需要的。否则,您需要拨打entities.Attach(person);

这应该有效:

PeopleEntities entities = ObjectContextFactory.GetPeopleEntities();
var person  = entities.People.Single(p => p.Id == id); // or some other way to get the person in question
// make changes to person ...
entities.SaveChanges();

答案 1 :(得分:1)

试试这个:

public void UpdateEntity(Entity entity) {
   var entityKeyObj = DataContext.Entity.Where(i => i.ID == entity.ID).First();
   entity.EntityKey = entityKeyObj.EntityKey;
   DataContext.ApplyCurrentValues("Units",entity);
   SaveChanges();
}

答案 2 :(得分:0)

var entity = context.Table.Single(predicate);
entity.Field = "stuff";
context.SaveChanges();