2013-11-02 84 views
4

我想爲我的MVC 5 Web應用程序設置一些種子數據,但它似乎並沒有爲IdentityUser創建任何數據。當我檢查App_Data文件夾是空的(顯示所有文件都是啓用)ASP.NET身份數據庫種子

這裏是我的WebAppDatabaseInitializer.cs

public class WebAppDatabaseInitializer : DropCreateDatabaseIfModelChanges<WebAppDbContext> 
{ 
    protected override void Seed(WebAppDbContext context) 
    { 
     var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
     var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); 

     string name = "Admin"; 
     string password = "123456"; 
     string test = "test"; 

     //Create Role Test and User Test 
     RoleManager.Create(new IdentityRole(test)); 
     UserManager.Create(new ApplicationUser() { UserName = test }); 

     //Create Role Admin if it does not exist 
     if (!RoleManager.RoleExists(name)) 
     { 
      var roleresult = RoleManager.Create(new IdentityRole(name)); 
     } 

     //Create User=Admin with password=123456 
     var user = new ApplicationUser(); 
     user.UserName = name; 
     var adminresult = UserManager.Create(user, password); 

     //Add User Admin to Role Admin 
     if (adminresult.Succeeded) 
     { 
      var result = UserManager.AddToRole(user.Id, name); 
     } 
     base.Seed(context); 
    } 
} 

和我的Global.asax.cs

public class MvcApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 
     GlobalConfiguration.Configure(WebApiConfig.Register); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
     Database.SetInitializer(new WebAppDatabaseInitializer()); 
    } 
} 

任何想法可能會出錯?

+1

是否出現問題?你能以管理員身份登錄嗎? Seed()是否在調試器中命中? –

+0

試圖用該帳戶登錄時出現錯誤: 無法附加文件'D:\ Libraries \ Documents \ Visual Studio 2013 \ Repo \ WebApp \ WebApp \ WebApp.Web \ App_Data \ aspnet-WebApp-20131019024822.mdf '作爲數據庫'aspnet-WebApp-20131019024822'。 – teh0wner

+0

以下是堆棧跟蹤:http://pastebin.com/TDW3MZWw – teh0wner

回答

3

問題在於正在初始化的DbContext與我在ApplicationUser中使用的DbContext不同,因此它不起作用。

+2

你能詳細說明一下嗎?我有類似的問題。我同時實現了Migrations和DbContext Seed方法,但沒有一個被觸發。 –

相關問題