我需要为我的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");
}
}
满足我要求的正确方法是什么?
答案 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