views:

95

answers:

1

Hi

I have 2 entities a Department and an Employee. 1 Department can have many Employees. I would like to clear all the Employees from an existing Department, and also add a new Employee to that same department and then save the changes. It must be within a single transaction.

However when I try execute the code below I get a key violation error on the database. It seems that the clear is not deleting the items in the DepartmentEmployee table, and then inserting the new Employee.

Employee newEmployee = GetNewEmployee();
department.Employees.Clear();
department.Employees.Add(newEmployee);
EntityContext.ApplyPropertyChanges("SetName", department);
EntityContext.SaveChanges();

Any help with this would be greatly appreciated. Thanks.

+1  A: 

I don't think you can do this in one call to SaveChanges. The Entity Framework does not guarantee any specific order of operations. So I don't think there is any way to force the DELETE to come before the INSERT without an additional call to SaveChanges.

On the other hand, you probably can do it in one database transaction. Just do it inside a new TransactionScope.

Try:

using (var t = new TransactionScope())
{
    Employee newEmployee = GetNewEmployee();
    department.Employees.Clear();
    EntityContext.SaveChanges();
    department.Employees.Add(newEmployee);
    EntityContext.ApplyPropertyChanges("SetName", department);
    EntityContext.SaveChanges();
    t.Complete();
}
Craig Stuntz
Hi, thanks for your reply. I tried your suggestion and it did work for the most part. The only thing I'll add is I had to Load() the Employee collection before clearing it, otherwise when saving to the database the same issue occurs.
dnoxs
You only need to `Load()` before `SaveChanges()` if your DB has no cascade.
Craig Stuntz