John John
John John

Reputation: 1

.NET Core console application, where is the connection string stored

Inside Visual Studio 2019 I have created a .NET Core console application. Then I use the below command to map existing database -

PM> Scaffold-DbContext "Server=.\MSSQL;Database=SchoolDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

The above command mapped all the tables inside the SchoolDB database. But I have the following question -

  1. inside my asp.net core web application, where is the connection string saved? So I can change it when I move my console application from test to the live environment.

Here is how my console application looks like after running the above command, where I can not find any configuration file to store the connection string -

enter image description here

Upvotes: 1

Views: 6237

Answers (1)

atiyar
atiyar

Reputation: 8305

The Scaffold-DbContext command should create a class SchoolDBContext in a file named SchoolDBContext.cs and it should be placed in the directory you specified with the -OutputDir parameter in the command. This class has a OnConfiguring method where the connection string is defined as -

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("your_connection_string");
    }
}

If you want SchoolDBContext to be placed in a separate directory, you can use the -ContextDir parameter in the command to specify it, like -

Scaffold-DbContext "your_connection_string" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir DbContext

EDIT:
If you want to put the connection string to a config file -

  1. add a .json file (e.g. appconfig.json) at the root of your project and put the following content in it -
{
  "ConnectionStrings": {
    "myDbConn": "your_connection_string"
  }
}
  1. in the solution explorer, right click on the appconfig.json file and select Properties. Set the value of Copy to Output Directory to Copy Always.
  2. install the Microsoft.Extensions.Configuration.Json package
  3. modify the OnConfiguring method to -
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var config = new ConfigurationBuilder()
        .AddJsonFile("appconfig.json", optional: false).Build();

    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer(config.GetConnectionString("myDbConn"));
    }
}

Upvotes: 4

Related Questions