如何使用EntityFramework将对象更新保存到数据库?

时间:2014-04-15 18:20:22

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

我有以下情况:

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对象更新保存回数据库。员工确实存在于数据库中。使用区块应该包含哪些内容?

2 个答案:

答案 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()
  }
}

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

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

答案 1 :(得分:0)

您需要在ObjectContext上调用SaveChanges