3

我需要为我的 MVC 应用程序创建默认角色(管理员和用户)和默认用户(我的管理员)。我正在使用代码优先方法。我是 MVC 新手,对迁移了解不多。

我尝试了以下代码,但我的表(pages_RolesUserProfile)仍然是空白的:

 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");
            }
        }

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

4

1 回答 1

4

Have you set your database initializer?

For example, add this code to your Application_Start() method in Global.asax

System.Data.Entity.Database.SetInitializer(new OutlinerDbInitializer());

I presumed that your class for initialization has this signature:

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

Try looking this example:

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

于 2013-10-24T09:16:18.860 回答