Home > Back-end >  Change DB name for Entity Framework DbContext
Change DB name for Entity Framework DbContext

Time:05-26

I have inherited an application which is using Entity Framework to access a SQL Server database. The DbContext class has the constructor as shown below, where BuildingPermits is the name of the initial catalog.

I would like to be able to switch between databases (with the same connection) via a config file instead of changing the code.

How can I accomplish this?

public BuildingPermitsDbContext() : base("BuildingPermits")
{
    Database.SetInitializer<BuildingPermitsDbContext>(null);
}

CodePudding user response:

You can try this.

using System.Configuration;

public BuildingPermitsDbContext() : base(DatabaseName())
{
    Database.SetInitializer<BuildingPermitsDbContext>(null);
}

private static string DatabaseName()
{ 
   var db = ConfigurationManager.AppSettingss["desiredDbName"];
   return db;
}
  • Related