User Authentication with EntityFrameworkCore and MySQL DB not working

.net-core asp.net-ajax asp.net-core c# entity-framework-core

Question

I am developing a .Net Core Web Application using Entity Framework and MySQL and when I try to register as a user, I get the following message.

An unhandled exception occurred while processing the request.
InvalidOperationException: Connection must be valid and open to commit transaction
MySql.Data.MySqlClient.MySqlTransaction.Commit()

This is my DB Context

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

    }
}

}

And this is my Startup code

    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();

    }

--UPDATE----

I Found out that the Authentication mechanism is done by Ajax not EF, the problem seems to stem from this line of code.

    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
   PROBLEM LINE====>         var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation(3, "User created a new account with password.");
                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }
1
1
3/31/2017 5:12:47 AM

Accepted Answer

I was having this exact same problem amonst a few others the other night. It's some kind of issue with async and the Oracle MySQL provider. If you override your DbContext's dispose method and put a breakpoint in there, you see the context gets disposed before some of the sign in steps are done. I found another SO question (can't find it right now on mobile), that had similar issues and recommended replacing Oracle MySQL package with this one:

https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

This fixed the problem and another problem I was having related to handling of varbinary data types longer than 255 when adding migrations.

Also remember the DbContext is loaded into the DI container in the "scoped" lifetime (by default), which means it is a single instance per http request, so make sure your code or any middleware you have in place isn't disposing the DbContext after getting it from the service container.

0
3/31/2017 6:03:59 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow