无法使用.NET Core 2.0连接到SQL 2008数据库。
无法使用.NET Core 2.0连接到SQL 2008数据库。
更新\n我无法使用“Windows身份验证”(域)用户使其工作。但是使用“SQL Server身份验证”用户,一切都按预期工作。\n原始问题\n我的连接字符串:Server=ip;Database=dbname;User Id=xxx\\user;Password=pass;
\n连接字符串位于appsettings.json中,如下所示:\n{\n \"Logging\": {\n \"IncludeScopes\": false,\n \"LogLevel\": {\n \"Default\": \"Warning\"\n }\n },\n \"ConnectionStrings\": {\n \"ConnectionString\": \"Server=ip;Database=dbname;User Id=xxx\\user;Password=pass;\"\n }\n}\n
\n然后我将其传递给“Startup.cs”文件中的一个静态类,如下所示:\n
public void ConfigureServices(IServiceCollection services) { // 添加框架服务。 services.AddMvc(); Orm.DatabaseConnection.ConnectionString = Configuration["ConnectionStrings:ConnectionString"]; }
\n这是我初始化连接的地方:\n
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); } } }
\n这是我的控制器:\n
public string Get() { using (var databaseConnection = Orm.DatabaseConnection.ConnectionFactory()) { var sections = databaseConnection.Query("SELECT * FROM myTable").ToList(); return sections.ToString(); } }
\n在这一行中:\n
var databaseConnection = Orm.DatabaseConnection.ConnectionFactory();
\n返回:\n
ServerVersion:“'databaseConnection.ServerVersion'引发了一个'System.InvalidOperationException'类型的异常” Message: “无效操作。连接已关闭。” Source: “System.Data.SqlClient” StackTrace: “at System.Data.SqlClient.SqlConnection.GetOpenTdsConnection()\n at System.Data.SqlClient.SqlConnection.get_ServerVersion()”
\n我在new SqlConnection
上遇到了这个错误:“错误CS0119:\'SqlConnection\'是一个类型,在给定的上下文中无效”
。\n但是由于这些错误,程序的执行并不会停止。\n应用程序然后在以下行上停止:\n
var sections = databaseConnection.Query("SELECT * FROM myTable").ToList();
\n我使用Dapper作为我的ORM(而不是EntityFramework)。在\"myTable\" SQL表中只有17行和5列,所以应该加载得很快。\n我尝试了各种不同的连接字符串,但总是失败。如果我尝试使用.NET Framework 4.5,一切都正常。问题出在.NET Core 2.0上。\n欢迎任何修复它的建议,因为我已经在这上面花了太多时间了。
无法使用.NET Core 2.0连接到SQL 2008数据库的原因是连接字符串中的错误以及代码中的编译错误。解决方法是修复连接字符串和代码中的错误。
首先,为了避免连接池问题,需要在连接字符串中添加“Pooling=false;”。修改后的连接字符串如下:
Server=ip;Database=dbname;User Id=xxx\user;Password=pass;Pooling=false;
其次,在代码中,需要将databaseConnection.Open()
添加到using
语句块中。修复后的代码如下:
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(); } }
在修复了连接字符串和代码后,编译错误应该消失,可以成功连接到SQL 2008数据库。