locked
Entity Framework: Attached Entities not Saving RRS feed

  • Question

  • 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.

    • Edited by ee99ee3 Wednesday, May 5, 2010 7:12 PM Code block messed up
    Wednesday, May 5, 2010 7:11 PM

Answers

  • If I understand your code correctly, then AccountRoles is a collection on the accountUser entity.  If this is the case, then you probably should not be using Attach here.  The semantics of Attach in the EF is essentially, "I assert that the way I am setting things up here is the way that things are in the database."  In other words, if you "attach" something to a collection, then you're telling EF that these entities already exist in that collection in the database.  Therefore, EF won't try to make any changes to the database when you SaveChanges.  Instead of using Attach, use Add on the collection.  This will tell EF that the entity is not in the collection in the database but should now be added to the collection, and hence the database will be updated appropriately when SaveChanges is called.

    Hope that helps.

    Thanks,

    Arthur

    Friday, May 7, 2010 4:09 PM