Microsoft.EntityFrameworkCore.Database.Connection[20004]

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

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

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 对象资源管理器连接到数据库,并从数据库属性中获取连接字符串,但这也不起作用

c# sql-server entity-framework-core asp.net-core-mvc
2个回答
0
投票

尝试使用这个语法

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

0
投票

所以我修正了错误。 解决方案是我必须在 SQL Server 配置中启用 TCP\IP 侦听。 问题不在于连接字符串。对于我的问题中的那些,一切都很好。 感谢您的帮助!

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