1

I'm using the following code to create the Session Factory with NHibernate. I'd like to specify this path with a relative path instead so that when my teammates and I merge our branches, we don't have to keep fixing the connection string. How can I accomplish this?

private static void InitializeSessionFactory(bool deleteSchemaOnClosing = false, bool regenerateSchemaOnOpening = false)
{
_sessionFactory = Fluently.Configure()
    .Database(MsSqlConfiguration.MsSql2008
                  .ConnectionString(
                      @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\MyProject\MyProjectCore\Fluent NHibernate\CoreDatabase.mdf"";Integrated Security=True;User Instance=True")
                  .ShowSql()
    )
    .Mappings(m =>
              m.FluentMappings
                  .AddFromAssemblyOf<User>())
    .ExposeConfiguration(cfg => new SchemaExport(cfg)
                                    .Create(deleteSchemaOnClosing,regenerateSchemaOnOpening))
    .BuildSessionFactory();
}

My app.config file looks like this:

<?xml version="1.0"?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="CoreDatabase.Properties.Settings.CoreDatabaseConnectionString"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CoreDatabase.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
        <add name="Fluent_NHibernate.Properties.Settings.CoreDatabaseConnectionString"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\CoreDatabase.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/></startup></configuration>

Thanks you!

2
  • can you add the path to the .config file and get it using "{0}", ConfigFile Key ..? you can use {0} params as well in the .config file also to read the value dynamically that way the change will only happen in 1 location instead of having to keep recompiling the code every time that value needs to change Commented Oct 16, 2012 at 23:15
  • Hi DJ KRAZE, can you please dumb it down for me? I am a complete rookie at this. Commented Oct 16, 2012 at 23:17

2 Answers 2

3

Take a look at SqlConnectionStringBuilder, you could do something like:

var rawStr = Settings.CoreDatabaseConnectionString.ConnectionString;
// retrieve the original connection string from config file

var conBuilder = new SqlConnectionStringBuilder(rawStr);
conBuilder.AttachDBFilename = Path.GetFullPath(
    Path.Combine(Environment.CurrentDirectory, "CoreDatabase.mdf"));
// if you're doing this in a web environment, swap Environment.CurrentDirectory 
// for HttpRuntime.AppDomainAppPath

_sessionFactory = Fluently.Configure()
    .Database(MsSqlConfiguration.MsSql2008
                  .ConnectionString(conBuilder.ToString())
                  .ShowSql()
    )
// rest of your configuration...
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Martin! Thanks for the response. I'm trying to figure out how to use var rawStr = Settings.CoreDatabaseConnectionString.ConnectionString; but it is not working. I also tried var rawStr = ConfigurationManager.ConnectionStrings["Fluent_NHibernate.Properties.Settings.CoreDatabaseConnectionString"].ConnectionString; which doesn't work either. Any suggestions?
From your app.config file it looks like you should have a class called settings which wraps access to the connection strings. If not, ConfigurationManager.ConnectionStrings["Fluent_NHibernate.Properties.Settings.Co‌​reDatabaseConnectionString"].ConnectionString should work - what error do you get if you do this?
Trying to extract the connection string with "Fluent_Nhibernate.Properies..." yields a null reference error for me. This is due to the fact that the ConfigurationManager contains two strings, one of which is {data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true} and the other is null
See codeproject.com/Tips/416198/… for how to get the connection string from your app.config file
Ah, I found the issue. The app.config file was in the project that had the database. This is all good and fine but I need to also have the same information in the app.config file of the project I am working in. Silly me. Thanks for all the help!
0

as an Example you could follow something like this .. this would be a way of Saving values to a .Config file but just to give you an example of how Parameters can be used inside of a .Config file take a look at this.

I will also append to my answer an easier way if you truly need an example

//Add config like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>

  </connectionStrings>
</configuration>


 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(
                                                          "MyConnectionString",
                                                          String.Format("DataSource={0};InitialCatalog={1};IntegratedSecurity={2}",
                                                                         "testing", "testing2", "Testing6")));
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("connectionStrings");
            MessageBox.Show(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)

Take a look at how to read from Config File as well try out the sample code on the link and step thru the code it will be an awesome learning experience... How to read Application Settings from .Config file

2 Comments

Hey DJ KRAZE, would you be able to help me with an example?
I gave you an example what are you having issues with.. please paste or show code where you are implementing the Params example thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.