Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the connection string value from hibernate.cfg.xml file?

I'm using Fluent NHibernate and need to get my Connection String from the connection.connection_string property on hibernate.cfg.xml file to create my Session Factory:

private static ISessionFactory SessionFactory {
   get {
      return = Fluently.Configure()
         .Database(MySQLConfiguration.Standard.ConnectionString(c => c.FromConnectionStringWithKey("MyConnStr")))
         .Mappings(m => m.FluentMappings.AddFromAssemblyOf<FooMap>())
         .ExposeConfiguration(c => c.Properties.Add("hbm2ddl.keywords", "none"))
         .BuildSessionFactory();
   }
}

I want to replace MyConnStr (that is in my web.config file) "c => c.FromConnectionStringWithKey("MyConnStr")" for the connection string from the hibernate.cfg.xml file.

I've tried use NHibernate.Cfg.Environment.ConnectionString, but it didn't work.

How can I get this?

Thank you.

like image 635
MCardinale Avatar asked Mar 12 '10 12:03

MCardinale


People also ask

What is Hibernate connection URL?

hibernate.connection.datasource. It represents datasource JNDI name which is used by Hibernate for database properties. hibernate.jndi.url. It is optional. It represents the URL of the JNDI provider.

What is Hibernate cfg XML?

Hibernate Configuration File(cfg file) is the file loaded into an hibernate application when working with hibernate. Hibernate uses this file to establish connection to the database server.It is an XML file which is used to define below information. Standard name for this file is hibernate.

What is the root element in Hibernate cfg XML file?

This is the root element having <session-factory> is a child element. <session-factory> contains database and mapping information. Way to register or load the driver. We provide fully qualified class name so that hibernate will figure out which class need to be load.


2 Answers

try this

NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();
string conString = cfg.Configuration.GetProperty(NHibernate.Cfg.Environment.ConnectionString);
like image 78
Jaguar Avatar answered Nov 03 '22 01:11

Jaguar


Updated for your updated question

public static string ConnectionString
{
  get
  {
    NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
    return cfg.GetProperty(NHibernate.Cfg.Environment.ConnectionString);
  }
}
like image 35
Nick Craver Avatar answered Nov 03 '22 01:11

Nick Craver