具有多个数据库服务器的 ServiceStack OrmLite
我正在围绕 servicestack 框架构建一个应用程序,并且需要能够访问 Oracle 和 MS Sql Server 中的数据.这是否可以使用 ORMLite,我似乎只能为应用程序设置一种方言,或者我错过了什么?
I'm building an app around the servicestack framework and need to be able to access data in both Oracle and MS Sql Server. Is this possible using ORMLite, it seems that I can only set a single dialect for the App or have I missed something?
推荐答案
是的,这是可能的,对此的支持已经内置在 OrmLiteConnectionFactory
中,请参阅 Master SQLServer + Sqlite 分片示例OrmLite 的项目主页.
Yes it is possible and support for this is already built into the OrmLiteConnectionFactory
, see the Master SQLServer + Sqlite shard example on OrmLite's project home page.
基本上,您首先要注册您的默认(或主)连接:
Basically you would register your default (or master) connection first with:
var dbFactory = new OrmLiteConnectionFactory(
"Data Source=host;Initial Catalog=RobotsMaster;Integrated Security=SSPI",
SqlServerDialect.Provider);
然后您将为您希望支持的每个其他连接注册一个命名连接,例如:
Then you would register a named connection for every other connection you wish to support, e.g:
dbFactory.RegisterConnection("shard-1",
"~/App_Data/{0}.sqlite".Fmt(shardId).MapAbsolutePath(),
SqliteDialect.Provider);
配置完成后,打开一个不指定名称的连接将打开一个到默认数据库的连接,例如:
Once that's configured, opening a connection without specifying a name will open a connection to the default database, e.g:
using (IDbConnection db = dbFactory.OpenDbConnection()) { ... } //Default DB
虽然您可以指定一个名称以打开到具有不同提供者的数据库的命名连接,例如:
Whilst you can specify a name to open up a named connection to a db with a different provider, e.g:
using (var dbShard = dbFactory.OpenDbConnection("shard-1")) { ... } //Named DB
手动使用不同的方言提供程序
不同 RDBMS 之间的 SQL 提供程序实现之间的差异包含在每个方言提供程序中.因此,如果您想针对特定的 ADO.NET 提供程序实现使用 OrmLite 的便捷扩展方法,您只需分配您希望使用的 ThreadStatic DialectProvider,例如:
Manually use different Dialect Providers
The differences between the SQL Provider implementations between different RDBMS's are contained within each dialect provider. So if you want to use OrmLite's convenience extension methods against an specific ADO.NET provider implementation you just need to assign the ThreadStatic DialectProvider you wish to use, e.g:
OrmLiteConfig.DialectProvider = SqlServerDialect.Provider;
var dbConn = new SqlConnection(SqlServerConnString);
dbConn.Select<Table>(); //All db access now uses the above dialect provider
这基本上是 OrmLiteConnectionFactory 中的 RegisterConnection
在幕后自动为您做的所有事情.
This is essentially all what RegisterConnection
in OrmLiteConnectionFactory automatically does behind the scenes for you.
到目前为止,OrmLite 的所有方言提供程序供参考:
For reference here are all the dialect providers for OrmLite up to this point:
- SqlServerDialect.Provider
- SqliteDialect.Provider(提供不同的 32/64 和 Mono 实现)
- MySqlDialect.Provider
- PostgreSqlDialect.Provider
- OracleDialect.Provider
- FirebirdDialect.Provider
相关文章