Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a program using entity framework, and depending on which computer it is run on, it will either connect to a remote database over the network or a local database on the local filesystem.

With entity framework, when I create an instance of MyDbContext (which inherits from entity framework's DbContext) it uses the code first naming conventions and will look in the app.config/web.config for a connection string with the same name (id) as the class -ie.. MyDbContact. Normally this is a very useful convention, but it doesn't suit my particular use case.

When my application loads, and before any querying takes place, I want to set the named connection string to a string of my liking - ie.. a connection string for a remote database or a local one.

Then, all future instances of MyDbContext will automatically obtain my custom connection string.

I do not want to have to hardcode the connection string in the web/app.config.

The program relies heavily on IoC/dependency injection and uses the domain driven design and repository+service patterns, and I also do not want to have to specify the connection string as a parameter to be passed to each repository when registering them with the resolver (autofac).

It seems logical to me that somewhere in the entity framework there must be a place for you to intercept this code first convention of retrieving the connection string from the web.config, and instead just pass in a custom string.

Am I way off, or is there actually a way of changing the default connection strings at runtime?

share|improve this question
add comment

1 Answer

One of the constructors of the DbContext class accepts a string, and the string can be the name of a connection string or a connection string.

To handle this using IoC you could define an abstraction to a connection string provider, something like this:

public interface IConnectionStringProvider
{
    string ConnectionString { get; }
}

public class MyContext : DbContext
{
    public MyContext(IConnectionStringProvider connectionStringProvider)
        : base(connectionStringProvider.ConnectionString)
    {
    }
}

public class ConnectionStringProvider : IConnectionStringProvider
{
    public ConnectionStringProvider()
    {
    }

    private string _connectionString = null;
    public string ConnectionString
    {
        get
        {
            if (_connectionString == null)
            {
                //initialise the connection string
                _connectionString = "Data Source=.;Initial Catalog ...";
            }
            return _connectionString;
        }
    }
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.