I am sure that we have all looked at the generated EDMX files with some architectural concerns. This is probably due to the business objects and the context being tightly coupled. I have other blogs for separating this out but once you do you end up with the need to have this metadata embedded connection string for the Entites to function. This string can be placed in the app or web config and you are off the the races but what happens when your EDMX is in another assembly that lives under a different namespace and you get the dreaded “Cannot locate metadata resource specified” error? You solve it be giving a connection string that points to the location of the file. Like so.
public static class EntityFrameworkConnectionStringHelper
{
public static string GetSqlConnectionString(string serverName, string databaseName)
{
var providerCs = new SqlConnectionStringBuilder
{
DataSource = serverName,
InitialCatalog = databaseName,
IntegratedSecurity = true
};
return GetSqlConnectionString(providerCs.ToString());
}
public static string GetSqlConnectionString(string providerConnectionString)
{
var namespaceString = typeof ($YourEdmxNameHere$Entities).Namespace;
var fullName = typeof ($YourEdmxNameHere$Entities).Assembly.FullName;
//This allows you to trim just the assembly name off the namespace while
//leaving the rest of the namespace
string trimmedNamespace = namespaceString.Remove(0, fullName.IndexOf(",") + 1);
var csBuilder = new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlClient";
csBuilder.ProviderConnectionString = providerConnectionString;
csBuilder.Metadata = string.Format(
"res://{0}/{1}.$YourEdmxNameHere$.csdl|res://{0}/{1}.$YourEdmxNameHere$.ssdl|res://{0}/{1}.$YourEdmxNameHere$.msl",
fullName, trimmedNamespace);
return csBuilder.ToString();
}
}
Enjoy!
8c916b14-228b-4b7d-b385-c3721ac5701c|1|5.0
Entity Framework, Productivity, Data Access