如何在ASP.NET Core中使用SqlClient?

Rob*_*abe 66 c# asp.net-mvc sqlclient .net-core asp.net-core

我试图在ASP.net核心中使用SQLClient库,但似乎无法使其工作.我发现这篇文章在线建议如何设置,但它不适合我:http://blog.developers.ba/using-classic-ado-net-in-asp-net-vnext/

我有一个简单的控制台应用程序包.我的project.json看起来像这样:

{
  "version": "1.0.0-*",
  "description": "DBTest Console Application",
  "authors": [ "" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",

  "compilationOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "System.Data.Common": "4.0.1-beta-23516",
    "System.Data.SqlClient" :  "4.0.0-beta-23516"
  },

  "commands": {
    "DBTest": "DBTest"
  },

  "frameworks": {
    "dnx451": { },
    "dnxcore50": {
      "dependencies": {
        "Microsoft.CSharp": "4.0.1-beta-23516",
        "System.Collections": "4.0.11-beta-23516",
        "System.Console": "4.0.0-beta-23516",
        "System.Linq": "4.0.1-beta-23516",
        "System.Threading": "4.0.11-beta-23516"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试以下代码:

using System;
using System.Data.SqlClient;

namespace DBTest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using (SqlConnection con = new SqlConnection(ConnStr)) {
                con.Open();
                try {
                    using (SqlCommand command = new SqlCommand("SELECT * FROM SAMPLETABLE", con)) {
                        command.ExecuteNonQuery();
                    }
                }
                catch {
                    Console.WriteLine("Something went wrong");
                }
            }

            Console.Read();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是得到以下错误:

在此输入图像描述

其他人有这个工作吗?

Mik*_*Dub 128

我想你可能在教程中错过了这一部分:

您需要从Nuget中获取,而不是引用System.Data和System.Data.SqlClient:

System.Data.Common和System.Data.SqlClient.

目前,这会在project.json - > aspnetcore50部分中为这两个库创建依赖关系.

"aspnetcore50": {
       "dependencies": {
           "System.Runtime": "4.0.20-beta-22523",
           "System.Data.Common": "4.0.0.0-beta-22605",
           "System.Data.SqlClient": "4.0.0.0-beta-22605"
       }
}
Run Code Online (Sandbox Code Playgroud)

尝试通过Nuget获取System.Data.Common和System.Data.SqlClient ,看看是否为您添加了上述依赖项,但简而言之,您缺少System.Runtime.

  • 我只需要通过`Nuget`添加`System.Data.SqlClient`,它与`.NET Core 1.1`中的`Dapper`一起使用. (5认同)
  • 我刚刚通过 Nuget 添加了 system.data.sqlclient 并且它有效 (2认同)

Moz*_*eeb 13

对于Dot Net Core 3,应使用Microsoft.Data.SqlClient

  • 对于从.NET Core 2.2迁移到.NET Core 3.0的任何人,此注释都可以挽救生命。将所有引用从System.Data.SqlClient替换为Microsoft.Data.SqlClient。 (3认同)