简体   繁体   中英

How to create Role in identity 2 in mvc5

here is my ApplicationUser and dbContext Class

public class ApplicationUser : IdentityUser
{

    public int? studentID { get; set; }
    [ForeignKey("studentID")]
    public virtual Student Student { get; set; }
}


public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {

    }
    public DbSet<ApplicationRole> ApplicationRoles { get; set; }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

and my Application Role class

public class ApplicationRole : IdentityRole
{
    public ApplicationRole(string name)
        : base(name)
    { }

    public ApplicationRole()
    { }

    public string Description { get; set; }
}

in my roles controller

public class RolesController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: /Roles/
    public ActionResult Index()
    {
        return View(db.Roles.ToList());
    }

db.Roles.ToList() shows nothing. but i have put some roles in database. db.Roles.ToList() returns no list. shows "Enumeration yielded no results"

Please help me. I want to crate roles and i have to use roleID to another table as foreign key. What wrong with this. i need a simple solution. Thank you.

Best way i find this to do is in the Migrations (Create if none exists):

internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(ApplicationDbContext context)
    {
        ParameterSeeder.Seed(context);
        RoleSeeder.Seed(context);
        UserSeeder.Seed(context);
    }
}

Then create a custom seeder for your users, ... and roles

internal static class RoleSeeder
{
    internal static void Seed(ApplicationDbContext context)
    {
        CreateRole("Admin", "Administrator");
    }

    private static void CreateRole(string name, string description)
    {
        var idManager = new IdentityManager();

        var newRole = new Role
        {
            Name = name,
            Description = description
        };

        if (!idManager.RoleExists(newRole.Name))
            idManager.CreateRole(newRole.Name, newRole.Description);
    }
}

Your IdentityManager, that you will use in the application more then just for seeds:

public class IdentityManager
{
    public bool RoleExists(string name)
    {
        var rm = new RoleManager<Role>(new RoleStore<Role>(new ApplicationDbContext()));

        return rm.RoleExists(name);
    }

    public bool CreateRole(string name, string description)
    {
        var rm = new RoleManager<Role>(new RoleStore<Role>(new ApplicationDbContext()));

        var newRole = new Role { Description = description, Name = name };
        var idResult = rm.Create(newRole);

        return idResult.Succeeded;
    }

    public bool CreateUser(User user, string password)
    {
        var um = new UserManager<User>(new UserStore<User>(new ApplicationDbContext()));
        um.UserValidator = new UserValidator<User>(um)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = false
        };

        user.UserInfo.ModifiedDate = DateTime.Now;
        user.UserInfo.ModifiedBy = "Migrations";
        user.UserInfo.ValidFrom = DateTime.Now;

        var idResult = um.Create(user, password);

        return idResult.Succeeded;
    }

    public bool AddUserToRole(string userId, string roleName)
    {
        var um = new UserManager<User>(new UserStore<User>(new ApplicationDbContext()));
        um.UserValidator = new UserValidator<User>(um)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = false
        };

        var idResult = um.AddToRole(userId, roleName);

        return idResult.Succeeded;
    }
}

Hope this gets you along...

One issue I see with your setup is

public DbSet<ApplicationRole> ApplicationRoles { get; set; }

You do not need to add this as Roles become available once you initialize your context as you have done in

private ApplicationDbContext db = new ApplicationDbContext();

Then your

// GET: Roles
public ActionResult AllRoles()
{
   return View(db.Roles.ToList());
}

should work.

When you add this, scaffolding might add a Dbset to your ApplicationDbContext in IdentityModels. Go ahead and delete it as the set of roles are already available in your context and you can access it with db.Roles

Now you can create a view for this. Something like

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
<table class="table">
<tr>
    <th>Role</th>
</tr>
@foreach (var item in Model)
{
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
}
</table>

There are multiple resources explaining how to seed users and roles, so I will describe how to create roles from the UI like for an admin console because I found most of the resources available to be either overly complicated or inconsistent with the way other custom models are handled.

In order to create a role from the UI you will need a controller like

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult CreateRole([Bind(Include = "Id, Name")] IdentityRole role)
    {
        if (ModelState.IsValid)
        {
            db.Roles.Add(role);
            db.SaveChanges();
            //If everything is good, save changes and redirect the user to the page with the list of all the roles.
            return RedirectToAction("AllRoles");
        }
        //If data is not valid return the original view with what the user has filled in.
        return View(role);
    }

This does the basic job but you can add the permissions, validations and error messages. Create an appropriate view for this controller which should not be too difficult. In the view for the model, use

@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM