0

I have the following scenario:

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

I'm not sure how to save the Employee object update back to the database. The employee does exist in the database. What should go in the using block?

1
  • how is your GetEmployee method work ? are you sure it returns the correct result? Commented Apr 15, 2014 at 18:32

2 Answers 2

1

Attach it before modifying, modify, then save changes.

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

You could also attach it, and then set the state to 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()
  }
}

And if you only want to send those fields in the update instead of all columns:

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()
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I'll try that. What would be the difference with the disconnected scenario here entityframeworktutorial.net/…?
Yes. Basically, you have to let the object state manager that the entity is modified after attaching.
Your first example doesn't set the state. If you assign properties to the object inside the entity using block, state doesn't need to be set?
It is set by the dbContext if the changes are performed after it is attached.
0

You need to call SaveChanges on your ObjectContext

4 Comments

I am calling SaveChanges(). It doesn't do anything. I've updated the OP.
You need to add the entity to the dbContext before calling SaveChanges.
Doesn't that attempt to insert a new record?
Sorry, misread you question, thought it said the object doesn't exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.