Reputation: 8237
simple question how do i change the connection string of the nhibernate at runtime ?
<property name="connection.connection_string" >value</property>
Upvotes: 2
Views: 3925
Reputation: 21
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/
Upvotes: 2
Reputation: 13457
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:
var configuration = new Configuration();
configuration.SetProperty("connection.connection_string", "...connection string...");
configuration.Configure();
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.
Upvotes: 3
Reputation: 24142
I would personally go with Enterprise Library
and its Data 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.
Upvotes: 1
Reputation: 8237
nevermind i got it.
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var root = XElement.Load(configuration.FilePath);
root.Elements().Where(m => m.Name.LocalName == "hibernate-configuration").First().Elements().First().Elements().Where(m => m.FirstAttribute.Value == "connection.connection_string").First().Value = cs;
root.Save(configuration.FilePath);
Upvotes: 2