如何传递两个连接字符串中NHibernate的在C#中? [英] How to Pass two connection string in Nhibernate in C#?

查看:170
本文介绍了如何传递两个连接字符串中NHibernate的在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序所面临的问题:我有两个数据库,我想与NHibernate来访问,但在CONFIGRATION文件我有一个数据库只有一个连接字符串。那么,如何可以通过多个连接字符串NHibernate的?

I faced problem in my application: I have two databases and I want to access both with NHibernate, but in the configration file I have only one connection string for one database. So how can I pass more than one connection string to NHibernate?

推荐答案

我通常在我的的app.config :

  <connectionStrings>
    <add name="connection1" connectionString="Data Source=;User ID=;Password=;" />
    <add name="connection2" connectionString="Data Source=;User ID=;Password=;" />
  </connectionStrings>



然后创建2个独立的(NHibernate的)配置与NHibernate配置文件(如果你有2个不同的数据库。)

then I create 2 separate (nhibernate) config files with nhibernate configurations (in case you have 2 different databases).

我使用一个类,它允许我创建一个会话工厂:

I use one class which allows me to create a session factory:

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

现在我可以创建自己的许多不同的会话工厂。具体配置:

Now I can create many different session factories with their own specific configuration:

var sessionFactory1 = new NHibernateSessionFactory("connection string 1", "sql.nhibernate").SessionFactory;

var sessionFactory2 = new NHibernateSessionFactory("connection string 2", "ora.nhibernate").SessionFactory;

您可以获取更多的这里

这篇关于如何传递两个连接字符串中NHibernate的在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆