How to switch between test and production databases with Entity Framework 5

谁都会走 提交于 2019-12-03 04:04:52

Use the config transforms. That's what they're there for. Admittedly, though, the config transforms are a little confusing because the debugger doesn't actually use them. Let me elaborate.

By default, you get three web.configs: Web.config, Web.Debug.config and Web.Release.config. The latter two, are combined with the first in the Solution Explorer, but you can expand Web.config to see them. Web.Debug.config and Web.Release.config are the transforms. They use a special XML-style syntax to allow you alter, or transform, settings in the main Web.config file. Each corresponds to a "Configuration", namely "Debug" and "Release", the two built into Visual Studio by default. You can add additional configurations as you need them.

Now, here's where things are confusing. The Debug configuration, despite its name, is never actually used when debugging. A better name would be perhaps Development or Staging; it's the configuration intended for when you deploy the site in a testing capacity, rather than to production. The Release config is for production. So, what you need is in your main Web.config, specify the connection string for your local development database. Then, in the Debug and Release configs, you add a transform to change that to the staging/production database connection strings, respectively. When you're debugging locally, the one the main web.config will be used, and then when you publish your application, you'll choose to either use Debug or Release, based on the environment you'll be deploying to, and then the transforms will be run to alter the published web.config appropriately.

For more information on transforms and how to write them, see: http://msdn.microsoft.com/en-us/library/dd465326(v=vs.110).aspx

Provide your connection name or connection string to the DbContext constructor.

public class YourContext : DbContext {

    public YourContext(string connection) : base(connection)
    {
    }

}

The string can be a variable your application modifies based on what database you want to connect to.

EDIT: updated the example so that now you have a constructor that accepts a string parameter which then passes it to the base class when instantiated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!