Monday, February 18, 2013

MVC - Entity Framework update an object



public void UpdateEmployee(Employee objEmployee)
{
using (DBEntities context = new DBEntities())
{
    //Must attach first and change the state to modified
    context.Employees.Attach(objEmployee);
    //If you are using .Net 4.1 then you can use this line instead:
   //context.Entry
    context.ObjectStateManager.ChangeObjectState(objEmployee, EntityState.Modified);
    context.SaveChanges();
}
}
 (OR)
public void UpdateEmployee(Employee objUpdatedEmployee)
{
using (DBEntities model = new DBEntities())
{
  Employee objoriginalEmployee = model.Employees.Single(e => e.EmployeeID == objUpdatedEmployee.EmployeeID);
        model.Employees.ApplyCurrentValues(objUpdatedEmployee);
        model.SaveChanges();
    }
}

No comments:

Post a Comment