Entity Framework Connection Strings

13. April 2011

We have all felt the pain of the entity framework connection string being embedded with meta data. I ran into this today in an integration test and had to create full qualified pointers to the dll to get past the dreaded “Unable to load metadata resource” error. Here are the fruits of that labor.

public class EntityFrameworkConnectionStringBuilder
   {
       public static string GetEFConnectionString(string serverName, string databaseName)
       {
           var providerCs = new SqlConnectionStringBuilder
                                {
                                    DataSource = serverName,
                                    InitialCatalog = databaseName,
                                    IntegratedSecurity = true
                                };
           Type type = typeof(YourEntities);  
          
           var csBuilder = new EntityConnectionStringBuilder
                               {
                                   Provider = "System.Data.SqlClient",
                                   ProviderConnectionString = providerCs.ToString(),
                                   Metadata =
                                       string.Format(
                                           "res://{0}/{1}.YourEDMX.csdl|res://{0}/{1}.YourEDMX.ssdl|res://{0}/{1}.YourEDMX.msl",
                                           type.Assembly.FullName, TrimAssemblyNameOffNamespace(type))
                               };
           return csBuilder.ToString();
       }
       private static string TrimAssemblyNameOffNamespace(Type type)
       {
           //If you have a . in your dll name or your namespace is different
           //you will have to adjust this. In this example the namespace was
           // Project.Common and the Namespace was      //Project.Common.Repositories.ObjectContexts
           var result = type.Namespace.Substring(type.Namespace.IndexOf(".")+1);
           return result.Substring(result.IndexOf(".") + 1);
       }
   }

Enjoy!

Entity Framework, Productivity , ,