如何在C#中传递Nhibernate中的两个连接字符串?

时间:2013-04-24 08:37:27

标签: c# nhibernate nhibernate-mapping

我在我的应用程序中遇到问题:我有两个数据库,我想用NHibernate访问它们,但在配置文件中我只有一个连接字符串用于一个数据库。那么如何将多个连接字符串传递给NHibernate呢?

2 个答案:

答案 0 :(得分:3)

我通常在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

答案 1 :(得分:1)

对于每个数据库,您需要一个自己的SessionFactory。如果省略NH配置中的ConnectionString,则可以在构建Sessionfactory时在Code中指定它:

var sessionFactory1 = new Configuration()
                    .Configure()
                    .SetProperty("connection.connection_string", "First Connection String").BuildSessionFactory();

var sessionFactory2 = new Configuration()
                    .Configure()
                    .SetProperty("connection.connection_string", "Second Connection String").BuildSessionFactory();