5

Please, help me to handle this situation:

I meaningly switched off AutoDetectChangesEnabled and I load my entities AsNoTracked() meaningly either.

And I can't update many-to-many relationship in this case:

Here is the code of Update method:

public void Update(User user)
{
  var userRoleIds = user.Roles.Select(x => x.Id);
  var updated = _users.Find(user.Id);

  if (updated == null)
  {
    throw new InvalidOperationException("Can't update user that doesn't exists in database");
  }

  updated.Name = user.Name;
  updated.LastName = user.LastName;
  updated.Login = user.Login;
  updated.Password = user.Password;
  updated.State = user.State;

  var newRoles = _roles.Where(r => userRoleIds.Contains(r.Id)).ToList();
  updated.Roles.Clear();
  foreach (var newRole in newRoles)
  {
    updated.Roles.Add(newRole);
  }

  _context.Entry(updated).State = EntityState.Modified;            
}

All simple fields, like Name, LastName updated. But the set of Roles for User doesn't get updated - it stays the same.

I tried loading Roles using

_context.Entry(updated).Collection("Roles").Load();

But I can't update this loaded set in any way.

I searched for similar items but failed to find the answer, thought it definitely already exists.

I'm really sorry for possible dublicate.

PS. I want to add that I don't want to delete or update child entities at all. A lot of existing answers suggest manually delete / add child entities to database in whole, but it is not suitable for me.

Roles are independent entities, any other user can use them.

I just want to update User_Role table in database, but I can't.

Eldho
  • 7,795
  • 5
  • 40
  • 77
Olga Kozlova
  • 133
  • 1
  • 7
  • Did you invoke `SaveChanges()` ? – Eldho Feb 15 '16 at 14:34
  • I think `User_Role` you added is not tracked by entity framework, hence updating the entity is not reflected to the database. `Attach` and try to update `_context.User_Role Attach(yourEntity);` then try to update – Eldho Feb 15 '16 at 14:38
  • 1
    I found one working way. Don't really know if it is sensible, but _context.ChangeTracker.DetectChanges(); works. I don't know if it possible to make the same manually. – Olga Kozlova Feb 15 '16 at 14:39
  • Surely I invoked SaveChanges, but later, in UnitOfWork Commit() method. No attaching, no updating child entities helps. Clild entities gets updated but not relationships between child and parent entities. – Olga Kozlova Feb 15 '16 at 14:41
  • 2
    Take a look at the details of `context.ChangeTracker.DetectChanges();` http://stackoverflow.com/a/15346082/1876572 I think to maintain relationship EF need to track the entities , Try the same without using `NoTracking()` – Eldho Feb 15 '16 at 14:50

0 Answers0