ca9163d9
ca9163d9

Reputation: 29159

Get the connection string not from App.Config?

The code generation of adding ADO.NET Entity Data Model adds the following class and App.config file.

public partial class MyDbContext : DbContext
{
    public MyDbContext()
        : base("name=MyDbContext")
    {
    }

App.Config

  <connectionStrings>
    <add name="MyDbContext" 
     connectionString="data source=...;initial catalog=...;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" 
     providerName="System.Data.SqlClient" />
  </connectionStrings>

However, I already have the connection string saved in Properties.Settings.Default.MyDbConnString. How to change the code to use the one in the properties?

Upvotes: 2

Views: 269

Answers (1)

Nkosi
Nkosi

Reputation: 247018

Note the constructor argument name for DbContext(String) constructor

public DbContext(string nameOrConnectionString);

Constructs a new context instance using the given string as the name or connection string for the database to which a connection will be made

You can use the full connection string in the constructor so update context to use the value stored in properties.

public partial class MyDbContext : DbContext {
    public MyDbContext()
        : base(Properties.Settings.Default.MyDbConnString) {
    }
}

And remove the on in the config file to avoid any conflicts.

Upvotes: 4

Related Questions