Dynamic connection for LINQ to SQL DataContext
- by Steve Clements
If for some reason you need to specify a specific connection string for a DataContext, you can of course pass the connection string when you initialise you DataContext object. A common scenario could be a dev/test/stage/live connection string, but in my case its for either a live or archive database. I however want the connection string to be handled by the DataContext, there are probably lots of different reasons someone would want to do this…but here are mine. I want the same connection string for all instances of DataContext, but I don’t know what it is yet! I prefer the clean code and ease of not using a constructor parameter. The refactoring of using a constructor parameter could be a nightmare. So my approach is to create a new partial class for the DataContext and handle empty constructor in there. First from within the LINQ to SQL designer I changed the connection property to None. This will remove the empty constructor code from the auto generated designer.cs file. Right click on the .dbml file, click View Code and a file and class is created for you! You’ll see the new class created in solutions explorer and the file will open. We are going to be playing with constructors so you need to add the inheritance from System.Data.Linq.DataContext public partial class DataClasses1DataContext : System.Data.Linq.DataContext { } Add the empty constructor and I have added a property that will get my connection string, you will have whatever logic you need to decide and get the connection string you require. In my case I will be hitting a database, but I have omitted that code. public partial class DataClasses1DataContext : System.Data.Linq.DataContext { // Connection String Keys - stored in web.config static string LiveConnectionStringKey = "LiveConnectionString"; static string ArchiveConnectionStringKey = "ArchiveConnectionString"; protected static string ConnectionString { get { if (DoIWantToUseTheLiveConnection) { return global::System.Configuration.ConfigurationManager.ConnectionStrings[LiveConnectionStringKey].ConnectionString; } else { return global::System.Configuration.ConfigurationManager.ConnectionStrings[ArchiveConnectionStringKey].ConnectionString; } } } public DataClasses1DataContext() : base(ConnectionString, mappingSource) { OnCreated(); } } Now when I new up my DataContext, I can just leave the constructor empty and my partial class will decide which one i need to use. Nice, clean code that can be easily refractored and tested. Share this post :