ASP.NET API:没有为此DbContext配置数据库提供程序 [英] ASP.NET API: No database provider has been configured for this DbContext

查看:224
本文介绍了ASP.NET API:没有为此DbContext配置数据库提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我的.Net Core API项目连接到MySql数据库.

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

这是我的上下文类:

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

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

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

        ...
}

这是我的 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.

在控制器中,我使用无参数构造函数实例化MyContext.

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

推荐答案

让我们尝试一下:

首先,在您的DbContext中创建OnConfiguring方法:

First, in your DbContext create OnConfiguring method :

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

第二,在您的ConfigureServices方法开始时,以这种方式配置DbContext:

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

services.AddDbContext<MyContext>();

这篇关于ASP.NET API:没有为此DbContext配置数据库提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆