Is there a way to modify the database connection string first?

database-first entity-framework


I have several databases, the schema of them are same. When I use database-first, the connection string is specified when I create the edmx file. I want to know, is there a way to change the connection string? This is, so I can choose which database to operate. Thx in advance!

5/9/2012 1:40:19 AM

Accepted Answer

Change the connection string in the web.config file.

    <add name="SandBoxEntities" connectionString="metadata=r... />

I abbreviated the actual connection string because it isn't important -- just wanted to give you an idea of what to look for in the web.config file.

You can also change your connection strings programatically. Check out Example 16.2. Programmatically modifying an EntityConnectionString.

5/9/2012 3:08:04 AM

Popular Answer

We do not store connection strings in our web.configs, so the accepted solution would not work for us. If you simply attempt to provide the connection string via the base DbContext constructor, you'll get the following exception:

Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.

To resolve this, create a partial class of your context as follows and format your connection string with the additional EF metadata (where MyContext is your context model name (e.g. your model name is MyModel.edmx, than the MyContext in code below is replaced with MyModel with all three extensions .csdl, .ssdl, .msl used)):

public partial class MyContext
    public MyContext(string connStr)
        : base(string.Format(@"metadata=res://*/MyContext.csdl|res://*/MyContext.ssdl|res://*/MyContext.msl;provider=System.Data.SqlClient;provider connection string='{0}'", connStr))

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow