Reputation: 1
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 -
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 -
Upvotes: 1
Views: 6237
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 -
.json
file (e.g. appconfig.json) at the root of your project and put the following content in it -{
"ConnectionStrings": {
"myDbConn": "your_connection_string"
}
}
appconfig.json
file and select Properties
. Set the value of Copy to Output Directory
to Copy Always
.Microsoft.Extensions.Configuration.Json
packageOnConfiguring
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