How to add user and user role to AspNetUserRole table

D Green

D Green

Feb 18 2015 5:08 PM
I have been stuck on this issue for a few days. I've search the web for answers and I'm still confused.  Please tell me how to add a userId and roleId to AspNetUserRole table.  The Roles have been setup in the AspNetRoles table. Below is the code that I used up to the point where I'm stuck.
Thank you in advance for your assistance
//Code begins here
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;

public partial class pages_Account_Register : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)


protected void btnRegister_Click(object sender, EventArgs e)
if (Page.IsValid)
//a connection for db where user info can be stored
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();

//Set ConnectionString to BkObserverDBConnectionString
userStore.Context.Database.Connection.ConnectionString =

UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

//Create new user and try to store in db
IdentityUser user = new IdentityUser();
user.UserName = txtUserName.Text;
user.Email = txtEmail.Text;
user.PhoneNumber = txtPhone.Text;

if (txtPassword.Text == txtConfirmPassword.Text)
//Create user object.
//Database will be created / expanded automatically.
IdentityResult result = manager.Create(user, txtPassword.Text);

//Create new User Role
IdentityUserRole userrole = new IdentityUserRole();
string roleId = "3";        //3 is Advertiser in AspNetRole table
userrole.UserId = user.Id;
userrole.RoleId = roleId;

//this is where I want to save user role to aspNetUserRole table
manager.AddUserToRole(userrole.UserId, userrole.RoleId);