MVC 5 Seed Users and Roles

前端 未结 7 1900
有刺的猬
有刺的猬 2020-11-28 01:56

I have been playing about with the new MVC 5, I have a few models, controller and views setup using code first migrations.

My question is how do I seed users and ro

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 02:27

    write this code in your Migration Configuration.

    note: Use ApplicationDbContext in Configuration Class.

        internal sealed class Configuration : DbMigrationsConfiguration
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = false;
        }
    
        protected override void Seed(ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.
    
            //  You can use the DbSet.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
                       context.Roles.AddOrUpdate(p =>
                p.Id,
                    new IdentityRole { Name = "Admins"},
                    new IdentityRole { Name = "PowerUsers" },
                    new IdentityRole { Name = "Users" },
                    new IdentityRole { Name = "Anonymous" }
                );
    
    
        }
    }
    

提交回复
热议问题