Question

I have a project called Authorization with CodeFirstRoleProvider class that inherits from default RoleProvider

public class CodeFirstRoleProvider : RoleProvider
{
    public override void CreateRole(string roleName)
        {
            if(string.IsNullOrEmpty(roleName)) return;
            using(var context = new SISContext())
            {
                var role = context.Roles.SingleOrDefault(rl => rl.RoleName == roleName);//Roles table exists in database 
                if(role == null)
                {
                    var newRole = new Role
                                      {
                                          RoleId = Guid.NewGuid(),
                                          RoleName = roleName
                                      };
                    context.Roles.Add(newRole);
                    context.SaveChanges();
                }
            }
        }
}

In my other project WebPortal I want to use above method in let's say following way

var _role = new CodeFirstRoleProvider();
            _role.CreateRole("Admin");
            _role.CreateRole("NonAdmin");

now where do I need to place this code in my webportal? so that these roles gets added to database for the first time when the application runs.

Suppose this program runs for first time and someone clicks the register button I want to have a dropdownlist with above roles mentioned. So, these roles need to be in database before register is clicked.

Once the roles are in database I don't need to worry for the accessing these values in future. One way would be manually writing the value in database but I don't want to do that, since I have this function I can use.

Was it helpful?

Solution

What If I do something like this?

[AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            var _role = new CodeFirstRoleProvider();//remove after role is added to database
            _role.CreateRole("Admiin");//remove after role is added to database
            _role.CreateRole("NonAdmin");//remove after role is added to database

            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

and once the roles are added to database i remove those code that does role adding.

OTHER TIPS

Take a look at this article on seeding the SimpleMembership database. Even if you are not using the SimpleRoleProvider the same principals should apply since you are using code-first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top