如何在mvc5中创建身份2中的Role

本文关键字:身份 中的 Role 创建 mvc5 | 更新日期: 2023-09-27 18:19:10

这是我的ApplicationUser和dbContext类

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

和我的Application Role类

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()无显示。但我把一些角色在数据库。db.Roles.ToList()不返回列表。显示"Enumeration yield no results"

请帮帮我。我想创建角色,我必须使用roleID到另一个表作为外键。这有什么不对。我需要一个简单的解决方案。谢谢你。

如何在mvc5中创建身份2中的Role

我发现最好的方法是在Migrations(如果不存在则创建):

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

然后为你的用户创建一个自定义的种子器,…角色和

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

您的IdentityManager,您将在应用程序中使用它,而不仅仅是用于种子:

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

我看到你的设置有一个问题

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

您不需要添加这个,因为一旦您初始化了上下文,角色就可用了,就像您在

中所做的那样
private ApplicationDbContext db = new ApplicationDbContext();

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

当你添加这个时,scaffolding可能会在IdentityModels中的ApplicationDbContext中添加一个Dbset。继续并删除它,因为角色集已经在您的上下文中可用,您可以使用db.Roles

访问它。

现在您可以为此创建一个视图。就像

@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>

有多种资源解释如何播种用户和角色,因此我将描述如何从UI(如管理控制台)创建角色,因为我发现大多数可用资源要么过于复杂,要么与其他自定义模型的处理方式不一致。

为了从UI创建一个角色,你需要一个像

这样的控制器
    [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);
    }

完成基本工作,但您可以添加权限、验证和错误消息。为这个控制器创建一个适当的视图应该不会太难。在模型视图中,使用

@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole