ASP.NET API: No database provider has been configured for this DbContext

匿名 (未验证) 提交于 2019-12-03 01:06:02

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!