如何配置和获取 DbProviderFactory

ADO.NET 编程如何配置和获取 DbProviderFactory

1、注册 DbProviderFactory#

machine.configapp.configweb.config 中存储提供程序和连接字符串信息。

下面以 SQLite 的配置为例,说明具体配置过程:

1.1 在 app.config 中的配置文件片段#

<configuration>
    <system.data>
        <DbProviderFactories>
            <remove invariant="System.Data.SQLite" />
            <add name="SQLite Data Provider" invariant="System.Data.SQLite"
                 description=".NET Framework Data Provider for SQLite"
                 type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
        </DbProviderFactories>
    </system.data>
    <connectionStrings>
        <add name="Sqlite" providerName="System.Data.SQLite" connectionString="test.db" />
    </connectionStrings>
</configuration>

1.2 获取 DbFactory 对象#

只需传入参数 "System.Data.SQLite"DbProviderFactories.GetFactory() 方法即可

1.3 一些需要注意的地方#

SQLite 分为 32-bit 和 64-bit,Precompiled Binaries 也分为 带bundle 和 不带bundle

  • 对于 带bundle 的,表示动态库是混合模式编译的,只需 System.Data.SQLite.dll 文件即可
  • 对于 不带bundle 的,除了 System.Data.SQLite.dll 文件还需要复制相应的 SQLite.Interop.dll文件

还有一点需要注意的是,工程中目标平台与 SQLite 的对应关系

  • Any CPU 和 x86 对应 SQLite 32-bit(Any CPU 要看编译时是否勾选了“首选32位”选项,如果没勾选且在 64位 系统运行,则会使用 64位 SQLite)
  • x64 则对应 SQLite 64-bit
  • 如果选择 不带bundle 的 SQLite,则文件组织结构如下:
项目目录/
├── System.Data.SQLite.dll
├── x86/
│   └── SQLite.Interop.dll       # 32 位
└── x64/
    └── SQLite.Interop.dll       # 64 位

❤️ 如果这篇文章对你有帮助,欢迎赞助支持我继续维护 ❤️

☕ Support me ⚡ 爱发电赞助