Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更改Nhibernate连接字符串_C#_Nhibernate_Linq To Xml - Fatal编程技术网

C# 更改Nhibernate连接字符串

C# 更改Nhibernate连接字符串,c#,nhibernate,linq-to-xml,C#,Nhibernate,Linq To Xml,简单的问题:如何在运行时更改nhibernate的连接字符串 <property name="connection.connection_string" >value</property> 值 没关系,我明白了 Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var root =

简单的问题:如何在运行时更改nhibernate的连接字符串

 <property name="connection.connection_string"  >value</property>
没关系,我明白了

        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);

我个人会使用
企业库
及其
数据访问应用程序块
,在实例化会话API时为NHibernate会话API提供适当的命名连接字符串

DAAB具有基于配置文件实例化
DbConnection
的功能。因此,您可以使用多个连接字符串定义,并告诉DAAB要使用什么连接,然后将其传递给您的NHibernate会话,以便您可以同时针对多个数据存储使用NHibernate


使用这种方法将避免您在运行时弄乱配置文件,甚至允许您创建自己的连接实例,而无需立即在配置文件中定义它们。

动态修改app.config有点可怕

我建议不要将您的连接字符串存储在其他nhibernate设置中。将各种连接字符串保留在其他位置(例如在appSettings中),然后直接根据NH配置设置适当的连接字符串:

var configuration = new Configuration();
configuration.SetProperty("connection.connection_string", "...connection string...");
configuration.Configure();

只需确保您的配置文件中未指定connection.connection\u字符串设置,因为只有当该设置尚未存在时,configuration.SetProperty才会正常工作。

当您需要根据某些条件切换连接时(例如,一个网站具有live和demo模式,每个网站都具有不同的连接字符串),那么最好实现从DriverConnectionProvider继承的类,并将该类设置为配置文件中connection.provider配置属性的值。
请参阅

通常建议不要在部署应用程序后使用app.config,建议将连接字符串config存储在本地应用程序设置中。如果用户没有权限更改程序文件目录中的文件,该怎么办?正如jonnii所说,这是个坏主意。