简体   繁体   中英

EntityFramework Core Database.EnsureCreated doesn't create database

I create a project with dotnetcore and entity framework core. I use MySql database and I added dependency to SapientGuardian.EntityFrameworkCore.MySql version 7.1.19 .

I created a SeedData class where initialize my database:

public class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (MyDbContext context = new MyDbContext(serviceProvider.GetRequiredService<DbContextOptions<MyDbContext>>())) {
            context.Database.EnsureCreated();
        }
    }
}

The call to seed class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Other code

    SeedData.Initialize(app.ApplicationServices);
}

And the configuration of service:

public void ConfigureServices(IServiceCollection services)
{
    // Other code

    // Add database
    services.AddDbContext<MyDbContext>(options => {
            options.UseMySQL(Configuration.GetConnectionString("DefaultConnection"));
    });

    services.AddScoped<Microsoft.EntityFrameworkCore.Infrastructure.IDbContextOptions, Microsoft.EntityFrameworkCore.DbContextOptions<MyDbContext>>();
}

When I start the project I get an exception on EnsureCreate call. Exception message say Authentication failed but if I manually create database (without tables) my connection string works fine and EnsureCreated simply create tables for my entities.

What's wrong? It's a problem with SapientGuardian.EntityFrameworkCore.MySql ?

I had the same problem you described. It looks like the SapientGuardian provider might simply have an incomplete implementation in this version.

The SapientGuardian project's readme file actually suggests using a more actively maintained provider such as Pomelo.EntityFrameworkCore.MySql . So I switched my project to Pomelo. Now the call to EnsureCreated creates the database as expected and does not have an authentication failed exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM