2014-04-15 66 views
0

我有以下情形:如何使用EntityFramework将对象更新保存到数据库?

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对象更新到数据库中。员工确实存在于数据库中。在使用块中应该怎么做?

+0

你的'GetEmployee'方法是如何工作的?你确定它会返回正确的结果吗? –

回答

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

我会尝试。与这里断开连接的场景有什么区别http://www.entityframeworktutorial.net/update-entity-in-entity-framework.aspx? – 4thSpace

+0

所以根据你的编辑,他们基本上是一样的东西。 – 4thSpace

+0

是的。基本上,你必须让对象状态管理器在连接后修改实体。 – dugas

0

你需要调用SaveChanges您的ObjectContext

+0

我打电话给SaveChanges()。它什么都不做。我已经更新了OP。 – 4thSpace

+0

在调用SaveChanges之前,您需要将实体添加到dbContext。 – dugas

+0

是不是试图插入新记录? – 4thSpace

相关问题