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

How to use SqlClient in ASP.NET Core?

我正在尝试在 ASP.net Core 中使用 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"
      }
    }
  }
}

然后我尝试以下代码:

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();
        }
    }
}

但是得到如下错误:

还有其他人成功了吗?

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

Instead of referencing System.Data and System.Data.SqlClient you need to grab from Nuget:

System.Data.Common and System.Data.SqlClient.

Currently this creates dependency in project.json –> aspnetcore50 section to these two libraries.

"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"
       }
}

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

编辑: 根据莫扎特的回答,如果您使用的是 .NET Core 3+,请参考 Microsoft.Data.SqlClient

试试这个 打开你的 projectname.csproj 文件 它对我有用。

<PackageReference Include="System.Data.SqlClient" Version="4.6.0" />

您需要在里面添加这个 Reference "ItemGroup" 标签。

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