Entity Framework: Attached Entities not Saving

Posted by blog on Stack Overflow See other posts from Stack Overflow or by blog
Published on 2010-05-05T19:06:58Z Indexed on 2010/05/05 19:18 UTC
Read the original article Hit count: 212

Filed under:

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.

© Stack Overflow or respective owner

Related posts about entity-framework