Search code examples
c#linqapp-configdbml

Reference class property in app.config?


Me and a collegue of mine are working on an application that connects to a database, using LINQ(and subsequently DBML files). Each one of us has their own connection string in order to work on the own database like so:

public class DbConfig
{    
   public static string conStr = @"My connection string";
   public static string conStr = @"His connection string";
}

Every time each one of us works on their part of the project, we just comment out the other connection string. My connection is if i can reference any of the two conString properties in the app.config file used by the DBML file. Thank you.


Solution

  • You can use you machine name to do this, using the code like that:

    public static class ConnectionString
    {
        public static string Get
        {
            get
            {
                if(ConfigurationManager.ConnectionStrings.Count == 0)
                    throw new Exception("No connection strings");
    
                var machineConnectionString = ConfigurationManager.ConnectionStrings["ConStringPrefix" + Environment.MachineName];
                var genericConnectionString = ConfigurationManager.ConnectionStrings["DefaultConString"];
                return  machineConnectionString ?? genericConnectionString;
            }
        }
    }
    

    And then in you app.config you will have:

    <connectionStrings>
        <add name="ConStringPrefix@MyPCName" connectionString="Data Source=.\sqlexpress;Initial Catalog=DatabaseName;Integrated Security=true" providerName="System.Data.SqlClient" />
        <add name="ConStringPrefix@MyFriendPcName" connectionString="Data Source=.\sqlexpress;Initial Catalog=DatabaseName;Integrated Security=true" providerName="System.Data.SqlClient" />
        <add name="nhibernate.conexao" connectionString="Data Source=.\sqlexpress;Initial Catalog=DatabaseName;Integrated Security=true" providerName="System.Data.SqlClient" />
    </connectionStrings>