2014-05-22 82 views
0

我在Configuration.cs文件的種子方法如下代碼:的UserManager <ApplicationUser> .Create()的返回null

var userStore = new UserStore<ApplicationUser>(); 
var manager = new UserManager<ApplicationUser>(userStore); 

IdentityResult result = manager.Create(new ApplicationUser() { UserName = "[email protected]", Email = "[email protected]", Name = "Martin Tracey" }, "password"); 
if (result.Succeeded) { Console.WriteLine("User created successfully"); } 
else { 
    Console.WriteLine("Something went wrong. result is "+result.ToString()); 
    foreach (var error in result.Errors) Console.WriteLine(error); 
} 

無論出於何種原因,manager.Create調用返回null

任何想法爲什麼這個方法會返回null?

回答

0

我想通了!這是一個非常簡單的解決方案。

我的userStore變量沒有允許它訪問和寫入數據庫的DbContext。簡單的解決方案是使用傳遞給Seed方法的上下文。現在就像一個魅力!見下:

protected override void Seed(MyFirstWebApplication.Models.ApplicationDbContext context) 
{ 
    if(!context.Users.Any(u => u.Email == "[email protected]")) 
    { 
     var userStore = new UserStore<ApplicationUser>(context); 
     var manager = new UserManager<ApplicationUser>(userStore); 
     var user = new ApplicationUser() { UserName = "[email protected]", Email = "[email protected]", Name = "Martin Tracey" }; 
     IdentityResult result = manager.Create(user, "password");} 
    } 
} 
相關問題