I am using C#, Visual Studio 2010 and Entity Framework 4. I have an assembly that contains multiple entity models. Project requirements are such that I am not storing any connection information in the app.config.
I have written a method that returns an entity connection string when I supply the name of the model I wish to load.
public static string GetEntityConnectionString(string modelName)
{
const string providerName = "somedatabaseprovider";
string metadata = string.Format(@"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", modelName);
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder
{
Provider = providerName,
ProviderConnectionString = GetProviderConnectionString(),
Metadata = metadata
};
return entityBuilder.ToString();
}
I now want to make it a little more bullet-proof by passing the entity model type, instead of a literal string for the model name. When I am editing the entity model in Visual Studio, the Properties window for MyModel (of type ConceptualEntityModel) contains a property called 'Entity Container Name' that shows MyEntities, and another property called 'Namespace' which shows MyModel.
At design-time, the type that I have access to is MyEntities. How can I derive th开发者_StackOverflow中文版e value stored in the 'Namespace' property of the ConceptualEntityModel at run-time?
This comes a few months late, but I put this idea up for discussion. I got the Conceptual Entity Model namespace property from any one of the Entities (tables) in the model, as follows:
string namespaceName = EDMInstance.Entity.EntitySet.ElementType.NamespaceName;
So I have an entity data model called "NITESMOVE_EDM" containing an entity "NM_PATHS", and create the entity metadata locations string as follows:
// create an instance of the Data Model
NITESMOVE_EDM EDMinst = new NITESMOVE_EDM();
// create a connection string builder
System.Data.EntityClient.EntityConnectionStringBuilder entityBuilder = new System.Data.EntityClient.EntityConnectionStringBuilder();
// Set the Metadata location, by querying an Entity in the model
entityBuilder.Metadata = string.Format(@"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", EDMinst.NM_PATHS.EntitySet.ElementType.NamespaceName);
This could be useful in conjunction with the advice given here: MSDN How to: Build an EntityConnection Connection String
Well, if your goal is to make this "bulletproof," this won't work. The string you call modelName
is not actually the model name, but the resource name. In your case it coincidently happens to be the same as the model name, but that isn't always true.
精彩评论