Microsoft.EntityFrameworkCore.Database.Connection[20004]



我创建了一个ASP.NET Core MVC应用程序来使用现有的SQL Server数据库。我使用Scaffold创建了所需的模型和数据库上下文。然后我写了一些代码来从数据库表中获取一些数据,但当我试图通过应用程序获取数据时,我在控制台中遇到了以下错误(我在这里更改了数据库名称(:

Microsoft.EntityFrameworkCore.Database.Connection[20004]
使用与服务器"localhost"上的数据库"dbname"的连接时出错。

和下一个

Microsoft.EntityFrameworkCore.Query[10100]
迭代上下文类型"dbname.dbnameContext"的查询结果时发生异常。

我试图用连接字符串进行操作,但没有得到任何结果。已尝试排除Trusted_Connection=true。将连接字符串硬编码为选项,并检查错误。

我的appsettings.json:

"ConnectionStrings": {
"FirstConnection": "Server=localhost;Database=dbname;Trusted_Connection=True;",
"SecondConnection": "Server=localhost;Database=dbname2;Trusted_Connection=True;"
}

启动

public void ConfigureServices(IServiceCollection services)
{
// string conFirst = Configuration.GetConnectionString("FirstConnection");
services.AddDbContext<IDatabaseContext, dbnameContext>(opt => opt.UseSqlServer("Server=localhost;Database=dbname;Trusted_Connection=True"));
services.AddTransient<ISomeService, SomeService>();
services.AddControllersWithViews();
}

谢谢!

PS:我试图通过VS SQL Server对象资源管理器连接到数据库,并从数据库的属性中获得了连接字符串,但也不起作用

尝试使用此语法

"Data Source=localhost;Initial Catalog=dbname;Integrated Security=SSPI;"

所以我修复了这个错误。解决方案是,我必须在SQL服务器配置中启用TCP/IP侦听。问题不在连接字符串中。有了我的问题,一切都很好。谢谢你的帮助!