如何在C#中的Nhibernate中传递两个连接字符串?
作者:互联网
我在应用程序中遇到问题:我有两个数据库,我想使用NHibernate来访问这两个数据库,但是在配置文件中,一个数据库只有一个连接字符串.那么如何将多个连接字符串传递给NHibernate?
解决方法:
我通常在app.config中定义连接字符串:
<connectionStrings>
<add name="connection1" connectionString="Data Source=;User ID=;Password=;" />
<add name="connection2" connectionString="Data Source=;User ID=;Password=;" />
</connectionStrings>
然后我用nhibernate配置创建2个单独的(nhibernate)配置文件(如果您有2个不同的数据库).
我使用一个类,该类允许我创建会话工厂:
public class NHibernateSessionFactory
{
private ISessionFactory sessionFactory;
private readonly string ConnectionString = "";
private readonly string nHibernateConfigFile = "";
public NHibernateSessionFactory(String connectionString, string nHConfigFile)
{
this.ConnectionString = connectionString;
this.nHibernateConfigFile = nHConfigFile;
}
public ISessionFactory SessionFactory
{
get { return sessionFactory ?? (sessionFactory = CreateSessionFactory()); }
}
private ISessionFactory CreateSessionFactory()
{
Configuration cfg;
cfg = new Configuration().Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, this.nHibernateConfigFile));
// With this row below Nhibernate searches for the connection string inside the App.Config.
// cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, System.Environment.MachineName);
cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionString, this.ConnectionString);
#if DEBUG
cfg.SetProperty(NHibernate.Cfg.Environment.GenerateStatistics, "true");
cfg.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true");
#endif
return (cfg.BuildSessionFactory());
}
}
现在,我可以使用自己的特定配置创建许多不同的会话工厂:
var sessionFactory1 = new NHibernateSessionFactory("connection string 1", "sql.nhibernate").SessionFactory;
var sessionFactory2 = new NHibernateSessionFactory("connection string 2", "ora.nhibernate").SessionFactory;
您可以找到更多信息here.
标签:nhibernate,nhibernate-mapping,c 来源: https://codeday.me/bug/20191031/1972010.html