繁体   English   中英

更改现有Asp.Net MVC 5(身份2)应用程序的种子方法?

[英]Change seed method for an existing Asp.Net MVC 5 (Identity 2) application?

如何向现有的Asp.Net Mvc / Identity 2网站添加固定角色(例如Admin)?

在链接http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/中 ,有以下代码正是我想做的。 但是,自应用程序以来,是否将执行Seed函数? (我已经有一些代码, var lookup1 = new List<L1>{new L1 {...},...}; tableL1.ForEach(l => context.tableL1.AddOrUpdate(p=>p.Title, l)); context.SaveChanges();Seed函数中播种一些查找表。)。 向已经在线的应用程序添加角色的正确方法是什么?

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

    protected override void Seed(AspNetIdentity.WebApi.Infrastructure.ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

        var user = new ApplicationUser()
        {
            UserName = "SuperPowerUser",
            Email = "taiseer.joudeh@gmail.com",
            EmailConfirmed = true,
            FirstName = "Taiseer",
            LastName = "Joudeh",
            Level = 1,
            JoinDate = DateTime.Now.AddYears(-3)
        };

        manager.Create(user, "MySuperP@ss!");

        if (roleManager.Roles.Count() == 0)
        {
            roleManager.Create(new IdentityRole { Name = "SuperAdmin" });
            roleManager.Create(new IdentityRole { Name = "Admin"});
            roleManager.Create(new IdentityRole { Name = "User"});
        }

        var adminUser = manager.FindByName("SuperPowerUser");

        manager.AddToRoles(adminUser.Id, new string[] { "SuperAdmin", "Admin" });
    }
}

如果要播种数据库,则必须在Package Manager控制台中 Enable-Migrations

我想您已经完成了此操作,因为您已经拥有Configuration.cs文件。

configuration类的构造函数中,确保将AutomaticMigrationsEnabled设置为false否则将重新创建数据库。

public Configuration()
{
    AutomaticMigrationsEnabled = false;
}

现在,您可以编译解决方案,并从Package Manager控制台运行 (确保在Default Project组合中选择了正确的项目):

Update-Database

要么

Update-Database -Verbose

如果您想收集更多信息。

并且您应该在数据库中看到新数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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