Home > OS >  How to pass connection string to DataContext in EF6
How to pass connection string to DataContext in EF6

Time:11-19

I have an ASP.NET MVC 5 web application and have the following piece of code:

public HAZID_DataContext() : base("HAZIDDEV")
{
    System.Data.Entity.SqlServer.SqlProviderServices.UseScopeIdentity = false;
}

I want to be able to set HAZIDDEV based on what my work environment is set to.

For example in the web config we have the following

  <connectionStrings>
    <add name="HAZIDTEST" connectionString="Server=DTISQLVS02\DEVELOPMENT;Database=HAZID;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
    <add name="HAZIDDEV" connectionString="Server=DTIDEV27;Database=HAZIDDEV;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
  </connectionStrings>

and would like to have a variable in the web config like this

<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

<add key="DefaultCulture" value="en" />
<add key="WorkEnvironment" value="Development"/>
<add key="PrefixDefaultCulture" value="false" />
<add key="SupportedCultures" value="en,fr" />
</appSettings>

So I could have a HAZIDDEV, HAZIDTEST and HAZIDPROD connection string and if I look at the application setting WorkEnvironment and it is Development then I will use HAZIDDEV as the connection.

Any help or insight would be much appreciated

CodePudding user response:

If your objective is to have separate connection strings for different environments then you should not be separating the connection string variables. Instead vary the value of the connection string.

Configure your DBContext object to be like the follwing:

public partial class HAZID_DataContext : DbContext
{
        public HAZID_DataContext()
        {
        }

        public HAZID_DataContext(DbContextOptions<HAZID_DataContext> options)
            : base(options)
        {
        }

        //Other codes goes here

}

Then inject the connection string in app startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<HAZID_DataContext>(opts =>
 opts.UseSqlServer(Configuration.GetConnectionString("HAZIDDEV")));
    
    ...
}

Then in the appsettings.json file for MVC Core:

{
  "ConnectionStrings": {
    "HAZIDDEV": "Data Source=.\SQLEXPRESS2012;Initial Catalog=dbname;Persist Security Info=True;User ID=abc;Password=abc"
  }
}

Or Read from web.config or other config file this way:

ConfigurationManager.ConnectionStrings["HAZIDDEV"].ConnectionString;

Just change the value of the connection string based on environments. Or have multiple connection strings as required.

  • Related