无法解决"A named connection string was used, but the name 'DefaultConnection' was not found in the app



我是.NET Core 6的新手,来自.NET Framework。

我在appsettings.json文件中配置了连接字符串,方法是:

"ConnectionStrings": {
"DefaultConnection": "Data Source=localhost;Initial Catalog=Plataforma;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;"
}

然后,我从一个现有的数据库中脚手架,这样:

Scaffold-DbContext -Connection name=DefaultConnection 
-Provider Microsoft.EntityFrameworkCore.SqlServer 
-OutputDir Models/DB -Force -NoPluralize

数据库已正确搭建。当我尝试使用它时,我会收到以下错误:

使用了命名连接字符串,但名称为"DefaultConnection"在应用程序的配置中找不到。请注意,命名只有在使用"IConfiguration"和服务提供者,例如在典型的ASP.NET Core应用程序中。

我看到创建的Db上下文在生成的Plataforma类中有这个方法,该类派生自DbContext:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("name=DefaultConnection");
}
}

调试时,我看到IsConfigured为false,所以它调用UseSqlServer方法,然后IsConfigured变为true。

通过阅读S.O.中的其他帖子,我将其添加到Program.cs文件中:

builder.Services.AddDbContext<Plataforma>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

然而,在调试时,我看到IsConfigured属性在调用OnConfiguring方法时仍然为false,因此它尝试使用该命名连接再次进行配置。

我该如何解决这个问题?

DbContext文件本身的名称和类名应该相同。此名称将在ConnectionStringProgram.cs中进行配置。

在您的案例中,DbContext的名称是DefaultConnection,正如您在scaffold命令name=DefaultConnection中指定的那样。

在Program.cs文件中注册DbContext应该使用与以下相同的上下文名称:

builder.Services.AddDbContext<DefaultConnection>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

有关更多相关详细信息,请参阅此Microsoft官方文档。

相关内容

最新更新