我正在将一个库移植到 .NET Core 2.1,因为它支持 DbProviderFactory。在大多数情况下,它运行良好 - 它可以编译,但在运行时出现错误:
System.ArgumentException: 'The specified invariant name 'System.Data.SqlClient' wasn't found in the list of registered .NET Data Providers.'
我使用 DbProviderFactories.GetFactoryClasses()
检查是否安装了任何提供程序,但似乎没有(结果表中有 0 行)。
所以我想我的问题是,如何为 .NET Core 安装数据提供程序?我在机器上安装了 .NET Framework 4.5,它可以毫无问题地获取数据提供程序。我不想将 System.Data.SqlClient
安装为本地项目的 Nuget,因为这会添加一个依赖项,使 DbProviderFactory
变得无关紧要。也就是说,我试图在一个使用我的库作为测试的项目中安装 System.Data.SqlClient
,但它仍然没有被选中。
最佳答案
在 .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";
}
}
}
如您所见,在本例中,我必须添加对我的提供程序“System.Data.CData.MySQL”的引用。
令人遗憾的是,您不能再获取所有可用的提供程序,但这是我们必须在 .NET Core 中使用的内容。
(信息来自this GitHub corefx issue)
关于c# - 在 .NET Core 2.1 中安装 .NET SQL Client 后,DbProviderFactories.GetFactoryClasses 不返回任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007836/