Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Core 2.0 scaffold-dbcontext Find ConnectionString in another project

I am using the EF Core 2.0 CLI command scaffold-dbcontext to reverse engineer poco classes from an existing DB (database first). The project that contains my appsettings.json file with the ConnectionString is different from the project that holds the poco classes generated by scaffold-dbcontext.

How can I get the scaffold-dbcontext command to find the ConnectionString in the appsettings.json file of another project?

like image 501
Scott Software Avatar asked Oct 04 '17 19:10

Scott Software


3 Answers

As stated in this you can now specify your connection string to be named, which looks like name=MyConnectionString. The name of your connection string corresponds with the one defined in your appsettings.json. Example:

Scaffold-DbContext  -Connection name=MyDB -Provider Microsoft.EntityFrameworkCore.SqlServer

where in appsettings.json you have something like this:

"ConnectionStrings": {
    "MyDB": Server=mydb.database.windows.net;Database=mydb;Trusted_Connection=True;Encrypt=True;"
}
like image 181
georgemr Avatar answered Oct 30 '22 11:10

georgemr


As of the time of this post, it doesn't appear that the scaffold-dbcontext command supports a appsettings.json connection string lookup. In other words, you must explicitly type the full connection string using the scaffold-dbcontext cli syntax:

Scaffold-DbContext -Connection "Server=(localdb)\ProjectsV13;Database=MyDbName;Trusted_Connection=True;" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Model -Context "MyDbContextName" -DataAnnotations -Force -Project MyEntitiesProject -StartupProject MyEntitiesProject

Not directly related to the OP, but just as a word to the wise... using the StartupProject option is helpful so you don't have to switch the Startup Project in Visual Studio to your entities project (e.g., MyEntitiesProject) in order to run the scaffold-dbcontext command.

There's a good link detailing the scaffold-dbcontext command options here.

Also be sure to have the following packages installed in your project in order to use the scaffold-dbcontext command in the nuget package manager console:

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.Design
like image 34
Scott Software Avatar answered Oct 30 '22 11:10

Scott Software


For me both answers was usefull. I wanted to generate the context in another project, so it was required to specify the startup project and select the project where I had to generate the context. So I use:

Scaffold-DbContext -Connection name=DefaultConnectionString -OutputDir DataModel -StartupProject NameofTheProject.API Microsoft.EntityFrameworkCore.SqlServer

like image 20
Simona Tocanie Avatar answered Oct 30 '22 09:10

Simona Tocanie