![](/img/trans.png)
[英]Create default roles and users using SimpleMembership MVC 4 - Code first approach
[英]How to create tables for roles and users automatically using identity framework with code first approach in asp.net mvc 5
我正在創建一個應用程序並制作了兩個表,但想通過代碼優先方法創建 AspNetRoles、AspNetUsers、AspNetUsersRoles 等表。 如果不使用 DB 優先方法或手動創建表,它將如何創建
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
createRolesandUsers();
}
private void createRolesandUsers()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
// In Startup iam creating first Admin Role and creating a default Admin User
if (!roleManager.RoleExists("SuperAdmin"))
{
// first we create Admin rool
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "SuperAdmin";
roleManager.Create(role);
//Here we create a Admin super user who will maintain the website
var user = new ApplicationUser();
user.UserName = "abc";
user.Email = "abc@gmail.com";
string userPWD = "password";
var chkUser = UserManager.Create(user, userPWD);
//Add default User to Role Admin
if (chkUser.Succeeded)
{
var result1 = UserManager.AddToRole(user.Id, "SuperAdmin");
}
}
//creating Creating Manager role
if (!roleManager.RoleExists("Manager"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "Manager";
roleManager.Create(role);
}
// creating Creating Employee role
if (!roleManager.RoleExists("Employee"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "Employee";
roleManager.Create(role);
}
}
我做過這樣的事情,沒有做過其他事情
如果我的問題正確,您只需要擴展 IdentityDbContext ,它是身份框架的一部分並生成遷移。 這是一種執行代碼優先的方法。 https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-core-cli
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.