首页 文章

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

提问于
浏览
59

我试图在 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();
        }
    }
}

但是得到以下错误:

在此输入图像描述

其他人有这个工作吗?

2 回答

  • 114

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

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

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

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

  • 0

    尝试这个打开你的projectname.csproj文件为我工作。

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

    你需要在里面添加这个参考“ItemGroup”标签。

相关问题