views:

22

answers:

1

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 the value stored in the 'Namespace' property of the ConceptualEntityModel at run-time?

A: 

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.

Craig Stuntz
Is there any way for me to get the model name from a given entity model type?
Welton v3.50
That isn't necessarily unique. You can have the same entity in multiple models (with code-first, e.g.).
Craig Stuntz
So am I better off sticking with the string literal value identifying the resource for the metadata? I'd rather be able to pass the type of the Entity Container Name, and derive the resource name from that (using reflection or some other method). BTW, the "entity model type" I was referring to in my previous comment was the Entity Model Container Name type, not an individual entity within a given model.
Welton v3.50
I don't know how to consistently, reliably, and in all cases derive a resource name. Remember, EDMX can come from physical files, too. Connection strings exist for a reason.
Craig Stuntz
In our case, all of our models are generated through Visual Studio using the Visual C# Items/Data/ADO.NET Entity Data Model template. I understand that in the future we may use different utilities for generating the model, but for right now we do have uniformity in our edmx structures because of the common template. If I could at least find a way to get the resource name give that assumption, it would give me a working solution for the time being.
Welton v3.50