更新
对于"Windows身份验证“(域)用户,我永远无法做到这一点。但是对于"SQL Server身份验证“用户,一切都像它应该的那样工作。
原始问题
我的connectionString:Server=ip;Database=dbname;User Id=xxx\user;Password=pass;
连接字符串位于appsettings.json中,如下所示:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"ConnectionString": "Server=ip;Database=dbname;User Id=xxx\user;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作为我的对象关系映射(而不是EntityFramework)。在"myTable“sql表中只有17行和5列,所以它应该加载得很快。
我尝试了各种不同的connectionStrings,但总是失败。如果我在.NET Framework4.5上尝试同样的方法,一切都会正常工作。问题出在.NET Core2.0。
任何关于修复的想法都是受欢迎的。因为我已经在这上面花了太多时间了。
发布于 2017-08-01 15:59:37
尝试添加databaseConnection.Open()
。
public string Get()
{
using (var databaseConnection = new SqlConnection(@"Server=ip;Database=dbname;User Id=xxx\user;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=xxx\user;Password=pass;Pooling=false;
编辑:我对连接字符串进行了硬编码,并删除了工厂以使示例更小
发布于 2017-08-03 00:50:45
尝试创建一个self-contained deployment,这应该会消除一些奇怪的依赖项。如果它能工作,那么至少你知道它是由一些程序集绑定类型的东西造成的。
例外的"error CS0119: 'SqlConnection' is a type, which is not valid in the given context"
看起来就是这样的。
https://stackoverflow.com/questions/45326115
复制相似问题