ASP.NET API: No database provider has been configu

2019-07-25 14:20发布

问题:

I am trying to connect to a MySql database from my .Net Core API project.

This is my context class:

public class MyContext : DbContext
{
    public MyContext() { }

    public MyContext(DbContextOptions<MyContext> options)
         : base(options) { }

    public MyContext(DbContextOptions options)
         : base(options) { }

        ...
}

and this is my startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    string MyConnectionString = "server=localhost;port=3306;user=root;password=*****;database=my_db";
    services.AddDbContext<MyContext>(options => options.UseMySQL(MyConnectionString));
}

I know this question has already been asked a million times, but I still can't fix it.

Edit: In controllers, I instantiate my MyContext using the parameterless constructor.

回答1:

Let's try something else :

First, in your DbContext create OnConfiguring method :

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder
           .UseMYSQL("... connection string ...");           
    }

Secondly, on the beginning of you ConfigureServices method, configure the DbContext this way :

services.AddDbContext<MyContext>();