views:

228

answers:

1

hi there,

am using MVC and Subsonic 3.0.0.3 but i cant seem to pin down a specific point for multiple database connection.

normally in normal .net i would have my 2 strings in the web.config file and have a database class for my project, within this db class i would do something like this:

try
        {
            conn.ConnectionString = server1;
            conn.Open();
        }
        catch (MySqlException)
        {
            conn.ConnectionString = server2;
            conn.Open();
        }

I am trying to pin down the one place in subsonic's created files where something like this would be best to place and maybe an up to date example on how to achieve it. I have googled etc but the examples shown are for an older subsonic.

many thanks

+1  A: 

If you look in Context.tt at line 35 you'll see the following code:

public <#=DatabaseName#>DB() 
{ 
    DataProvider = ProviderFactory.GetProvider("<#=ConnectionStringName#>");
    Init();
}

This is where the provider is getting setup for you so if you add a BackupConnectionStringName variable in Settings.ttinclude after the ConnectionStringName at line 20 then you should be able to check your connection is working and user your fallback if not. For example:

public <#=DatabaseName#>DB() 
{ 
    DataProvider = ProviderFactory.GetProvider("<#=ConnectionStringName#>");
    Init();
    try
    {
        DataProvider.CreateConnection();
    }
    catch(SqlException)
    {
       DataProvider = ProviderFactory.GetProvider("<#=BackupConnectionStringName#>");
       Init(); 
    }
}

NB You may need to do some clean up to make sure a connection is not left open by CreateConnection.

Adam
yep thats where i was going, great stuff thanks
minus4
var myconn = DataProvider.CreateConnection();myconn.Close();covers the closing of the successful attempt in the try block
minus4