views:

727

answers:

4

I want to use the connection string App.Config file. Also is it possible to use NHibernate connect to 2 databases (different connection strings) if so how?

+1  A: 

In case of maintaining 2 different DB connection Frederik Gheysels's link is the best answer.

AFAIK this is not possible to use standard App.config format like:

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="ConnString1" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=NhibernateDB;Integrated Security=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

NHibernate provides 3 ways to read config info:

Reading configuration from App.config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  </configSections>

  <!-- NHibernate Configuration -->
  <nhibernate>
    <add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
    <add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>
    <add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
    <add key="hibernate.connection.connection_string" value="Data Source=(local)\sqlexpress;Initial Catalog=NHibernateDB;user=sa;Password=;Integrated Security=true"/>
  </nhibernate>
</configuration>

Improved way of Reading configuration from App.config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>

  <!-- NHibernate Configuration -->
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="connection.connection_string">Data Source=(local)\sqlexpress;Initial Catalog= NHibernateDB;user=sa;Password=;Integrated Security=True;</property>
<mapping assembly="NHibernate_Test.BO"/>
    </session-factory>
  </hibernate-configuration>
</configuration>

Reading Configuration from hibernate.cfg.xml file

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8" ?>    
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=NHibernateDB; user=sa;Password=;Integrated Security=True</property>
    <property name="show_sql">false</property>
    <!--<property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>-->
    <mapping assembly="NHibernate_Test.BO" />
  </session-factory>
</hibernate-configuration>

I can suggest you to load config informations in the code like this:

public sealed class Persister : System.IDisposable
    {
        private NHibernate.ISessionFactory _sessionFactory;


        /// <summary> Configures NHibernate to access the data source and map entities to tables. </summary>
        public Persister()
        {
            System.Console.Out.WriteLine("Configuration of NHibernate...\n");
            const string connectionString = @"Data Source=(local)\sqlexpress;Initial Catalog=nhibernate;Integrated Security=SSPI";

            // Enable the logging of NHibernate operations
            log4net.Config.XmlConfigurator.Configure();

            // Create the object that will hold the configuration settings
            // and fill it with the information to access to the database
            NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
            configuration.Properties[NHibernate.Cfg.Environment.ConnectionProvider] = "NHibernate.Connection.DriverConnectionProvider";

            System.Console.Out.WriteLine("Use SQL Server database: ConnectionString = <"
                 + connectionString + ">\n");

            // These are the three lines of code to change in order to use another database
            configuration.Properties[NHibernate.Cfg.Environment.Dialect] = "NHibernate.Dialect.MsSql2000Dialect";
            configuration.Properties[NHibernate.Cfg.Environment.ConnectionDriver] = "NHibernate.Driver.SqlClientDriver";
            configuration.Properties[NHibernate.Cfg.Environment.ConnectionString] = connectionString;


            // Use NHibernate.Mapping.Attributes to create mapping information about our entities
            System.Console.Out.WriteLine("Generating the mapping information for NHibernate...\n");
            NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Enable validation (optional)
            using (System.IO.MemoryStream stream = NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(System.Reflection.Assembly.GetExecutingAssembly()))
            {
                configuration.AddInputStream(stream); // Send the mapping information to NHibernate configuration
            }

            // Create the table in the database for the entity Message
            System.Console.Out.WriteLine("Creating the table in the database for the entity Message...");
            new NHibernate.Tool.hbm2ddl.SchemaExport(configuration).Create(true, true);


            // Build the SessionFactory
            System.Console.Out.WriteLine("\n\nBuilding the session factory, end of the configuration\n\n");
            _sessionFactory = configuration.BuildSessionFactory();
        }


        public void Dispose()
        {
            // Do not forget to close the session factory when you are done with it
            _sessionFactory.Close();
        }
JMSA
+2  A: 

You can create multiple ISessionFactories; one for each database that you want to connect to.

Check this article.

Frederik Gheysels
A: 

It's possible with Fluent NHibernate. You can use a raw connection string, an app setting, or read from the connectionStrings section. An example of reading from the connectionStrings section is:

ISessionFactory factory = Fluently.Configure()
    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MyClass>())
    .Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey("connectionStringKey"))
    .BuildSessionFactory();

As Frederik mentioned, you can work with multiple databases by configuring multiple session factories.

Jamie Ide
A: 

For the first part of your question:

<property name="connection.connection_string_name">ConnStringName</property>

Then declare your <connectionStrings> as usual. @JMSA is wrong.

Diego Mijelshon