Creating a Database Object in DAAB from a Dynamic ConnectionString
When using the Database Access Application Block in the Microsoft Enterprise Library, you can define a Database object from a ConnectionString in your project app or web.config. In my latest project, I needed to create a ConnectionString from information the user enters in the login form. After a little trial and error, this is what I came up with.
using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.Practices.EnterpriseLibrary.Data.Sql; public static class DatabaseFactory { public static Database CreateDatabase(string connectionString, string provider) { DbProviderFactory factory = DbProviderFactories.GetFactory(provider); Database database = null; if(String.IsNullOrEmpty(connectionString)) throw new ArgumentNullException("connectionString can not be null or empty."); if (factory == null) throw new ArgumentException("provider was not a valid type"); switch (factory.GetType().ToString().ToLower()) { case "system.data.sqlclient" : database = new SqlDatabase(connectionString); break; default: database = new GenericDatabase(connectionString, factory); break; } return database; } }
Our team already has built some helper classes around working with DAAB Database objects, so it made more sense for us to continuing working with them instead of just creating a DbConnection directly. I did find a link on David Hayden’s blog that outlines that approach instead. The code is at the bottom of the post.




