我正在将一个库移植到 .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
在一个使用我的库作为测试的项目中,它仍然没有被选中。
在 .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 中使用的内容。
(信息来自这个 GitHub corefx 问题 https://github.com/dotnet/corefx/issues/4571)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)