I am using DB first method, EF 4.1 with DbContext POCO code gen.
My database has a many-to-many relationship as shown below:
Employee
EmployeeId
EmployeeName
Account
AccountId
AccountName
EmployeeAccount
EmployeeId
AccountId
The problem occurs when I am trying to update an Employee, and change their account assignment to a pre existing account, so I am basically doing this as below:
using(context)
{
var query = from e in context.Employees.Include(f => f.Accounts)
where e.EmployeeId == employeeId
select;
Employee emp = query.FirstOrDefault()
}
emp.EmployeeName = "Test";
emp.Accounts.Clear();
Account act = MethodThatLooksUpAccountByName("SomeAccountName");
emp.Accounts.Add(act);
using(context)
{
context.Accounts.Attach(act);
emp.State = EntityState.Modified;
context.Employees.Attach(emp);
context.SaveChanges();
}
The SQL being generated is executing an update on the [Employee] table, nothing for the [EmployeeAccount] at all, no delete no insert.
Try to remove (at least) the last
Attach. You also don’t need to set the state toModifiedbecause you are in an attached scenario (empis loaded from DB) and change tracking will recognize what did change:This should work in my opinion.
Edit after you changed the code in the question:
The second context performs its own change tracking. So it doesn’t recognize that you have removed the accounts and added a new one. It should work the following way:
I have the feeling, it’s not what you want. Did you have done the changes of the employee (clearing old accounts and adding new account) in a state detached from the last context?
The problem with many-to-many collection is that you must load or attach the old
Accountcollection in the context where you want to clear or change it. There is no way to trigger any DELETE or INSERT statements on the link table by setting any scalar property or by setting a state on any entity. Only detection of changes in the collections will EF cause to update the link table.