如何在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);
}
}

我做过这样的事,没有做过其他

如果我答对了你的问题,你只需要扩展作为Identity Framework一部分的IdentityDbContext并生成迁移。这是一种代码优先的方法。https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=dotnet-核心cli

相关内容

  • 没有找到相关文章

最新更新