在.NET Core 2.1中安装.NET SQL Client后,DbProviderFactories.GetFactoryClasses不返回任何结果

All*_*ine 7 c# dbproviderfactories .net-core

我正在将一个库移植到.NET Core 2.1,因为它支持DbProviderFactory.在大多数情况下它已经很好 - 它编译,但运行时我得到一个错误:

System.ArgumentException:'在已注册的.NET数据提供程序列表中找不到指定的不变名'System.Data.SqlClient'.

我曾经DbProviderFactories.GetFactoryClasses()检查过是否安装了任何提供程序,并且似乎没有(结果表中有0行).

所以我想我的问题是,如何为.NET Core安装数据提供程序?我在机器上安装了.NET Framework 4.5,它正在挑选数据提供程序而没有任何问题.我不想System.Data.SqlClient作为本地项目的Nuget 安装,因为这会添加一个依赖性,使得DbProviderFactory无关紧要.也就是说,我试图安装System.Data.SqlClient在一个使用我的库作为测试的项目中,但它仍然没有被选中.

Jos*_*VdM 11

在.NET Framework中,提供程序可通过machine.config自动获取,并且还在GAC中全局注册.在.NET Core中,不再有GAC或全局配置.这意味着您必须首先在项目中注册您的提供者,如下所示:

using System.Collections.Generic;
using System.Data.CData.MySQL; // Add a reference to your provider and use it
using System.Data.Common;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Register the factory
            DbProviderFactories.RegisterFactory("test", MySQLProviderFactory.Instance);

            // Get the provider invariant names
            IEnumerable<string> invariants = DbProviderFactories.GetProviderInvariantNames(); // => 1 result; 'test'

            // Get a factory using that name
            DbProviderFactory factory = DbProviderFactories.GetFactory(invariants.FirstOrDefault());

            // Create a connection and set the connection string
            DbConnection connection = factory.CreateConnection();
            connection.ConnectionString = "Server = test, Database = test";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,在这种情况下,我必须添加对Provider的引用,"System.Data.CData.MySQL".

令人遗憾的是,您不能仅仅获得所有可用的提供程序,但这是我们必须在.NET核心中使用的.

(来自此GitHub corefx问题的信息)


小智 5

正如阿米尔之前提到的:

在.net core中你必须注册Factory

对于 SQL:DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);

但是,要执行此操作,您应该将System.Data.SqlClientnuget 包添加到您的项目中。

像这样(工具 - > Nuget包管理器 - >包管理器控制台)

Find-Package SQLClient
Install-Package System.Data.SqlClient -ProjectName YourProjectName
Run Code Online (Sandbox Code Playgroud)