无法使用 .NET Core 2.0 连接到 SQL 2008 数据库



>UPDATE

我永远无法与"Windows 身份验证"(域(用户一起完成这项工作。但是对于"SQL Server 身份验证"用户,一切都像预期的那样工作。

原始问题

我的连接字符串:Server=ip;Database=dbname;User Id=xxxuser;Password=pass;

连接字符串位于 appsettings.json 中,如下所示:

{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"ConnectionString": "Server=ip;Database=dbname;User Id=xxxuser;Password=pass;"
}
}

然后我从"Startup.cs"文件将其传递给静态类,如下所示:

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
Orm.DatabaseConnection.ConnectionString = Configuration["ConnectionStrings:ConnectionString"];
}

这是我启动连接的地方:

using System.Data.SqlClient;
namespace MyProject.Orm
{
public static class DatabaseConnection
{
public static string ConnectionString { get; set; }
public static SqlConnection ConnectionFactory()
{
return new SqlConnection(ConnectionString);
}
}
}

这是我的控制器:

public string Get()
{
using (var databaseConnection = Orm.DatabaseConnection.ConnectionFactory())
{
var sections = databaseConnection.Query("SELECT * FROM myTable").ToList();
return sections.ToString();
}
}

其中这一行:

var databaseConnection = Orm.DatabaseConnection.ConnectionFactory();

返回:

ServerVersion: "'databaseConnection.ServerVersion' threw an exception of type 'System.InvalidOperationException'"
Message: "Invalid operation. The connection is closed."
Source: "System.Data.SqlClient"
StackTrace: "at 
System.Data.SqlClient.SqlConnection.GetOpenTdsConnection()n   
at 
System.Data.SqlClient.SqlConnection.get_ServerVersion()"

我在new SqlConnection上收到此错误:"error CS0119: 'SqlConnection' is a type, which is not valid in the given context".

但是程序执行不会因为这些错误而停止。

然后,应用程序将挂起在以下行上:

var sections = databaseConnection.Query("SELECT * FROM myTable").ToList();

我正在使用Dapper作为我的ORM(不是EntityFramework(。在"myTable"中,sql 表只有 17 行和 5 列,因此它应该加载速度很快。

我尝试了各种不同的连接字符串,但它总是失败。如果我尝试使用.NET Framework 4.5进行相同的操作,则一切正常。问题是.NET Core 2.0。

欢迎任何关于修复它的想法。因为我已经花了很多时间在这上面。

尝试添加databaseConnection.Open()

public string Get()
{
using (var databaseConnection = new SqlConnection(@"Server=ip;Database=dbname;User Id=xxxuser;Password=pass;Pooling=false;"))
{
databaseConnection.Open();
var sections = databaseConnection.Query("SELECT * FROM myTable").ToList();
return sections.ToString();
}
}

若要避免注释中所述的连接池出现问题,请将Pooling=false;添加到连接字符串:Server=ip;Database=dbname;User Id=xxxuser;Password=pass;Pooling=false;

编辑: 我硬编码连接字符串并删除了工厂以使示例更小

尝试创建一个独立的部署,这应该消除奇怪的依赖关系。 如果它有效,那么至少你知道这是由于某些程序集绑定类型的东西。

例外"error CS0119: 'SqlConnection' is a type, which is not valid in the given context"闻起来像它。

最新更新