更改 Nibernate 连接字符串
简单的问题如何在运行时更改 nhibernate 的连接字符串?
<property name="connection.connection_string" >value</property>
simple question how do i change the connection string of the nhibernate at runtime ?
<property name="connection.connection_string" >value</property>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
动态修改你的 app.config 有点可怕。
我建议不要将连接字符串存储在其他 nhibernate 设置中。将各种连接字符串保留在其他地方(例如在 appSettings 中),然后直接根据 NH 配置设置适当的连接字符串:
只需确保配置文件中未指定 connection.connection_string 设置,因为configuration.SetProperty 仅在以下情况下才能正常工作该设置尚不存在。
Tinkering with your app.config on the fly is a bit horrible.
I'd suggest not storing your connection string amongst the other nhibernate settings. Keep your various connection strings elsewhere (e.g. in appSettings), then set the appropriate connection string directly against your NH Configuration:
Just make sure that the connection.connection_string setting is not specified in your config file, as configuration.SetProperty will only work correctly if the setting is not there already.
没关系,我明白了。
nevermind i got it.
当您需要根据某些条件切换连接时(例如拥有一个具有实时和演示模式的网站,每个网站都有不同的连接字符串),那么最好实现一个从 DriverConnectionProvider 继承的类,并将此类设置为连接的值配置文件中的 .provider 配置属性。
请参阅http://jasondentler.com/blog /2009/11/authentication-impersonation-and-dynamic-nhibernate-connection-strings/
When you need to switch connections based on some conditions (such as having one website with live and demo mode, each with different connection string) then it´s probably best to implement a class inherited from DriverConnectionProvider and set this class as value of the connection.provider configuration property in your config file.
See http://jasondentler.com/blog/2009/11/authentication-impersonation-and-dynamic-nhibernate-connection-strings/
我个人会使用
企业库
及其数据访问应用程序块
在实例化会话 API 时为 NHibernate 会话 API 提供正确命名的连接字符串。DAAB 具有基于配置文件实例化
DbConnection
的功能。因此,您可以使用多个连接字符串定义,并告诉 DAAB 使用哪个连接,然后将其传递给您的 NHibernate 会话,以便您可以同时使用 NHibernate 处理多个数据存储。使用这种方法将避免您在运行时弄乱配置文件,甚至允许您创建自己的连接实例,而无需立即在配置文件中定义它们。
I would personally go with
Enterprise Library
and itsData Access Application Block
to provide the NHibernate sessions APIs with proper named connectiong strings when instantiating a session API.The DAAB has the feature to instantiate a
DbConnection
based on the configuration file. So you could possibly use several connection strings definition, and tell DAAB what connection to use, then pass it to your NHibernate session so that you may work with NHibernate against multiple datastores at once.Using this approach will avoid you messing with the configuration file on runtime, and even allows you to create your own connections instance without having them defined in the configuration file at once.