【问题标题】:How to save object updates to database with EntityFramework?如何使用实体框架将对象更新保存到数据库?
【发布时间】:2014-04-15 18:20:21
【问题描述】:

我有以下场景:

public void UpdateEmployee(int empId, int deptId, int level)
{
  Employee emp = GetEmployee(empId);
  emp.DeptId = deptId;
  emp.Level = level;

  using (var mye = new MyEntity())
  {
    //this is having no effect?
    wc.SaveChanges()
  }
}

我不确定如何将 Employee 对象更新保存回数据库。该员工确实存在于数据库中。 using 块中应该放什么?

【问题讨论】:

  • 您的GetEmployee 方法效果如何?你确定它返回正确的结果吗?

标签: .net entity-framework c#-4.0


【解决方案1】:

在修改之前附加它,修改,然后保存更改。

public void UpdateEmployee(int empId, int deptId, int level)
{
  Employee emp = GetEmployee(empId);

  using (var dbContext = new MyDbContext())
  {
   dbContext.Employees.Attach(emp);
   emp.DeptId = deptId;
   emp.Level = level;
   //this is having no effect?
   dbContext.SaveChanges()
  }
}

您也可以附加它,然后将状态设置为已修改:

public void UpdateEmployee(int empId, int deptId, int level)
{
  Employee emp = GetEmployee(empId);
  emp.DeptId = deptId;
  emp.Level = level;    

  using (var dbContext = new MyDbContext())
  {
   dbContext.Employees.Attach(emp);
   dbContext.Entry(emp).State = EntityState.Modified;
   dbContext.SaveChanges()
  }
}

如果您只想在更新中发送这些字段而不是所有列:

public void UpdateEmployee(int empId, int deptId, int level)
{
  Employee emp = GetEmployee(empId);
  emp.DeptId = deptId;
  emp.Level = level;    

  using (var dbContext = new MyDbContext())
  {
   dbContext.Employees.Attach(emp);
   dbContext.Entry(emp).Property(p => p.DeptId).IsModified = true;
   dbContext.Entry(emp).Property(p => p.Level).IsModified = true;
   dbContext.SaveChanges()
  }
}

【讨论】:

  • 我会试试的。与此处entityframeworktutorial.net/… 断开连接的情况有什么区别?
  • 是的。基本上,您必须让对象状态管理器在附加后修改实体。
  • 你的第一个例子没有设置状态。如果使用block给实体内部的对象分配属性,就不需要设置state了?
  • 如果在附加后执行更改,则由dbContext设置。
【解决方案2】:

你需要在你的 ObjectContext 上调用SaveChanges

【讨论】:

  • 我正在调用 SaveChanges()。它什么也没做。我已经更新了 OP。
  • 您需要在调用 SaveChanges 之前将实体添加到 dbContext。
  • 这不是尝试插入新记录吗?
  • 对不起,误读了你的问题,以为它说对象不存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多