使用SimpleMembership MVC 4创建默认角色和用户 - 代码优先方法

时间:2013-10-24 08:55:58

标签: c# asp.net asp.net-mvc asp.net-mvc-4 ef-migrations

我需要为我的MVC应用程序创建默认角色(管理员和用户)和默认用户(我的管理员)。我正在使用代码第一种方法。我是MVC的新手,对迁移知之甚少。

我尝试了以下代码,但我的表格( webpages_Roles UserProfile )仍为空白:

 protected override void Seed(Outliner.Models.OutlinerDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

            var roles = (SimpleRoleProvider)System.Web.Security.Roles.Provider;
            var membership = (SimpleMembershipProvider)System.Web.Security.Membership.Provider;

            if (!roles.RoleExists("Admin"))
                roles.CreateRole("Admin");

            if (!roles.RoleExists("User"))
                roles.CreateRole("User");

            if (General.IsNull(membership.GetUser("admin", false)))
            {
                WebSecurity.CreateAccount("admin", "password");
            }
        }

满足我要求的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

您是否设置了数据库初始化程序?

例如,将此代码添加到Application_Start()

中的Global.asax方法
System.Data.Entity.Database.SetInitializer(new OutlinerDbInitializer());

我假设你的初始化类有这个签名:

public class OutlinerDbInitializer: DropCreateDatabaseIfModelChanges<Outliner.Models.OutlinerDbContext context> {
    ...
}

尝试查看此示例:

http://www.itorian.com/2012/10/entity-frameworks-database-seed-method.html