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

14 浏览
0 Comments

无法使用.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欢迎任何修复它的建议,因为我已经在这上面花了太多时间了。

0
0 Comments

问题原因:连接不上SQL 2008数据库的原因可能是由于一些程序集绑定类型问题导致的。

解决方法:尝试创建一个self-contained deployment,这样应该可以消除一些奇怪的依赖问题。如果这样做可以解决问题,那么至少可以确认是由于一些程序集绑定类型问题导致的。

异常信息"error CS0119: 'SqlConnection' is a type, which is not valid in the given context"表明可能是这个原因。

0
0 Comments

无法使用.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数据库。

0