AddDbContext 在 ASP.NET Core Razor 页面的配置服务中不起作用

问题描述 投票:0回答:2

我将 SQL Server 数据库反转到它们各自的类和上下文中,所有这些似乎都工作正常。

在 min 上下文类中,有一行代码指向连接字符串,如果保留它可以正常工作,但连接字符串完全嵌入到上下文文件中。

我尝试在上下文中对其进行注释,并通过

ConfigureServices
部分进行添加(这样我就可以在
appsettings.json
中使用 conn 字符串)使用

services.AddDbContext<myDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("dbconn")));

但是当我运行时,我收到错误:-

System.InvalidOperationException:“没有数据库提供程序 为此 DbContext 配置。提供者可以通过以下方式配置 重写 DbContext.OnConfiguring 方法或使用 AddDbContext 关于应用服务提供商。如果使用AddDbContext,那么 还确保您的 DbContext 类型接受

DbContextOptions<TContext>
对象在其构造函数中并将其传递给 DbContext 的基本构造函数。'

我在 Google 上尝试了很多方法,但总是遇到同样的错误,除非我取消注释上下文类文件中的硬编码连接字符串。

知道我做错了什么吗?

我已经尝试了很多谷歌回复,但都有相同的错误 - the:-

System.InvalidOperationException:“没有数据库提供程序 为此 DbContext 配置。提供者可以通过以下方式配置 重写 DbContext.OnConfiguring 方法或使用 AddDbContext 关于应用服务提供商。如果使用AddDbContext,那么 还确保您的 DbContext 类型接受

DbContextOptions<TContext>
对象在其构造函数中并将其传递给 DbContext 的基本构造函数。'

我从上下文类中注释掉了这一点:-

optionsBuilder.UseSqlServer("Server=MYSERVER\\MSSQL2017EXPRESS;Database=DBNAME;Trusted_Connection=True;user id=DBUSER;password=DBPASSWORD;");

这是startup.cs中的内容,但不起作用:-

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    //My DB conn
    services.AddDbContext<myDatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("dbconn")));

}

我需要能够从 appsettings.json 提供连接字符串,而不是将其硬编码到上下文类文件中。

c# entity-framework-core asp.net-core-mvc razor-pages
2个回答
3
投票

您很可能在您的上下文中缺少构造函数。

public myDatabaseContext(DbContextOptions<myDatabaseContext> options) : base(options) {
    //...
}

按照错误消息中的建议

如果使用

AddDbContext
,则 还确保您的 DbContext 类型接受
DbContextOptions<TContext>
对象在其构造函数中并将其传递给
DbContext
的基本构造函数。'


0
投票

您很可能缺少 Microsoft.EntityFrameworkCore.SqlServer 包。

© www.soinside.com 2019 - 2024. All rights reserved.