2

I need some help on adding roles to user in a many-many situation.

So I have User with many Role and Role has many User.

I figured my current Update() method in my repository wont work. How can I build a repository method that allows me to remove all previous roles and add new roles to user?

This is what I currently have:

    public User UpdateUser(User user, IEnumerable<Expression<Func<User, object>>> properties)
    {
        if (string.IsNullOrEmpty(user.UserId))
        {
            throw new InvalidOperationException("user does not exist");
        }
        else
        {
            db.Users.Attach(user);
            foreach (var selector in properties)
            {
                string propertyName = Helpers.PropertyToString(selector.Body);
                db.Entry(user).Property(propertyName).IsModified = true;
            }

        }

        db.SaveChanges();
        return user;
    }

Is this the right way to update a user? I'm assuming everything the detached. This is how I'm calling this to add roles to user:

        User user = new User();
        user.UserId = userId;
        user.Roles = new Domain.Role{ RoleId = 1}; //Assuming there is a role with ID = 1
        userRepo.UpdateUser(user, new List<Expression<Func<User, object>>>
                                      {
                                          u => u.Roles
                                      });
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

1 Answers1

1

If you are working in a detached scenario you might want to look into the object state manager. See these two answers for more info.

Entity Framework Code First - Add Child Entity to Parent by Primary Key

Save a relation with between two entities an N-N association

The first one is a simple example where a single child is added without roundtriping the db. The second one is more complex but I still haven't found a good way to clear the relationship without telling it which childs to delete.

There is a possibility I haven't looked at yet and it is to use the RelationshipManager which you can get from the ObjectStateManager. It contains a few methods to get releated collections so maybe you could use that somehow.

Community
  • 1
  • 1
Mikael Eliasson
  • 5,157
  • 23
  • 27