5

I use ASP.NET Identity 2.0 in my MVC application and I want to assign 2 default roles to the user who login to the system for the first time by adding 2 records to the AspNetUserRoles table with UserId and RoleId. Is there a practical way to to this? Or do I have to add these default roles using DBContext and Entity Framework, etc. (I use EF Code First)? Any help would be appreciated.

2 Answers 2

4

After creating the user record in Register post action

var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); 

You can add the roles

await UserManager.AddToRoleAsync(user.Id, "role1"); await UserManager.AddToRoleAsync(user.Id, "role2"); 
Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks for your reply. The oles can be assigned, but I cannot create new user in AspNetUsers table by using the first part of your code. Could you have a look at please?
On the other hand, I also need to add these new roles to the AspNetUserRoles table, but I am not sure if your code can also perform this.
@binary The first two lines of code are from default mvc5 template, thats how a new ApplicationUser / IdentityUser is inserted in database. The other two lines of code assign user to those roles, using asp.net-identity. In database inside AspNetUserRoles you will see two new entries {userId and role1Id} and {userId and role2Id}
1

You could do a check in the AccountController, Register method (the one with the HttpPost), something like: if (!MyDbContext.Users.Any()) {...}

And if there are no users, assign roles to the newly created user with: UserManager.AddToRoleAsync

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.