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

查看:37
本文介绍了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天全站免登陆