Paul
Paul

Reputation: 1875

Entity framework, multiple edmx to share connection string - is it possible?

I saw a number of related questions but none of them is exactly what I am looking for.

We are using one database and need to have separated edmx files, with different Model and ObjectContext class names. This results in having multiple connections string, which are different only in metadata part.

For now I ended up doing this:

Web.config

<connectionStrings configSource="connectionStrings.config"></connectionStrings>

connectionStrings.config

<connectionStrings> 

<add name="Entities" connectionString="metadata=res://*/Entity.Model.csdl|
res://*/Entity.Model.ssdl|res://*/Entity.Model.msl;
provider=CONNECTION STRING DATA GOES HERE"/> 

<add name="TwoEntities" connectionString="metadata=res://*/TwoEntity.TwoModel.csdl|
res://*/TwoEntity.TwoModel.ssdl|res://*/TwoEntity.TwoModel.msl;
provider=EXACTLY THE SAME CONNECTION STRING DATA GOES HERE"/> 

</connectionStrings> 

In my ObjectContext derived classes I do have the default generated constructors:

public Entities()
            : base("name=Entities", "Entities")
{
}

and

public TwoEntities()
            : base("name=TwoEntities", "TwoEntities")
{
}

What would be very nice is not to have two connection strings in .config file, but share the same connection sting from this file and somehow override the metadata part of it in each class.

Any suggestions on how to do this?

Upvotes: 5

Views: 3265

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364389

Yes it is possible but you cannot use EF connection string from configuration. You must built connection string manually in the application. ObjectContext supports multiple overloaded constructors. One of the is accepting EntityConnection. EntityConnection in turn can be constructed from MetadataWorkspace (class created from your EF metadata files) and DbConnection. You can add custom factory method to your derived context which will build MetadataWorkspace and DbConnection from shared DB connection string and pass them in EntityConnection.

public static Entities GetContext(string connenctionString) 
{
    MetadataWorkspace workspace = GetWorkspace(); // This should handle workspace retrieval
    DbConnection connection = new SqlConnection(connectionString); // Connection must not be openned
    EntityConnection entConnection = new EntityConnection(workspace, entConnection);
    return new Entities(entConnection);
}

private Entities(EntityConnextion entConnection) : base(entConnection)
{  } 

You will use this factory method instead of constructor. Make sure that GetWorkspace creates MetadataWorkspace only once per metadata set and store it internally for the lifetime of the application. Its creation is time consuming.

Upvotes: 5

Related Questions