Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindByEmailAsync() returns null always

Tags:

asp.net-core

My test code is for creating a new user if there isn't existed. and it check if user is existed, using FindByEmailAsync() method. but It returns null always, so it's creating same many users.

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

Here is my 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();

    /// ...
}

Also config.User.RequireUniqueEmail = true; is not working, because it's creating multiple users with same email address, but I don't see any an error.

What am I doing wrong? please advise me.

like image 861
Expert wanna be Avatar asked Sep 14 '16 15:09

Expert wanna be


1 Answers

Internally the UserManager is actually searching on the NormalizedEmail column. I would look in the database and see if that is getting populated correctly or not.

like image 131
Joe Audette Avatar answered Oct 10 '22 20:10

Joe Audette