Entity Framework: Attached Entities not Saving
- by blog
Hello:
I can't figure out why calling SaveChanges() on the following code results in no changes to the objects I attached:
// delete existing user roles before re-attaching
if (accountUser.AccountRoles.Count > 0)
{
foreach (AccountRole role in accountUser.AccountRoles.ToList())
{
accountUser.AccountRoles.Remove(role);
}
}
// get roles to add
List<int> roleIDs = new List<int>();
foreach (UserRole r in this.AccountRoles)
{
roleIDs.Add(r.RoleID);
}
var roleEntities = from roles in db.AccountRoles
where roleIDs.Contains(roles.id)
select roles;
accountUser.AccountRoles.Attach(roleEntities);
db.SaveChanges();
In the debugger, I see that the correct roleEntities are being loaded, and that they are valid objects. However, if I use SQL Profiler I see no UPDATE or INSERT queries coming in, and as a result none of my attached objects are being saved.