2016-09-14 152 views
1

我的測試代碼用於在不存在的情況下創建新用戶。 ,它使用FindByEmailAsync()方法檢查用戶是否存在。 但它總是返回null,所以它創建了相同的許多用戶。FindByEmailAsync()總是返回null

public HomeController(
    IUnitOfWork unitOfWork, 
    UserManager<User> userManager) 
{ 
    _unitOfWork = unitOfWork; 
    _userManager = userManager; 
} 

public async Task<IActionResult> Index() 
{ 
    var test = await _userManager.FindByEmailAsync("[email protected]"); 

    if (test == null) 
    { 
     // Add the user 
     var newUser = new User 
     { 
      UserName = "mark", 
      Email = "[email protected]", 
      Created = DateTime.Now, 
      Updated = DateTime.Now 
     }; 

     _unitOfWork.UserRepository.Insert(newUser); 
     _unitOfWork.Save(); 

     // password is 'admin' 
     await _userManager.CreateAsync(newUser, "admin"); 
    } 

    return View(); 
} 

這裏是我的startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    // add Identity 
    services.AddIdentity<User, IdentityRole>(config => 
    { 
     config.User.RequireUniqueEmail = true; 
     config.Password.RequiredLength = 4; 
     config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login"; 
    }) 
    .AddEntityFrameworkStores<MyContext>(); 

    /// ... 
} 

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    app.UseIdentity(); 

    /// ... 
} 

而且config.User.RequireUniqueEmail = true;不工作,因爲它創建多個用戶使用同一個電子郵件地址,但我沒有看到任何錯誤。

我在做什麼錯?請建議我。

回答

5

在內部,UserManager實際上是在NormalizedEmail列上進行搜索。我會查看數據庫,看看是否正確填充或不填充。