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
});