In .Net Core Entity Framework, there is no GUI in Visual Studio to create entities and context yet. But it can be easily done by Package Manager Console.
1. Install “Microsoft.EntityFrameworkCore.Tools” in NuGet
Install-Package Microsoft.EntityFrameworkCore.Tools
2. Install “Install-Package Microsoft.EntityFrameworkCore.SqlServer”
(If your database is not MS SQL, this needs to be modified to your db engine)
Install-Package Microsoft.EntityFrameworkCore.SqlServer
3. Run “Scaffold-DbContext” command.
(Specify the db engine you installed in step 2.
Set -ContextDir/-Context/-OutputDir to specify where models/context should be created.)
Scaffold-DbContext “Server=(localdb)\MSSQLLocalDB;Database=AdventureWorks;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -ContextDir Context -Context AdventureWorksContext -OutputDir Models
This is the result.
Troubleshooting
If your project is .NET Standard, you might have the following error.
Startup project ‘AdventureWorks.Ef’ targets framework ‘.NETStandard’. There is no runtime associated with this framework, and projects targeting it cannot be executed directly. To use the Entity Framework Core Package Manager Console Tools with this project, add an executable project targeting .NET Framework or .NET Core that references this project, and set it as the startup project; or, update this project to cross-target .NET Framework or .NET Core.
This is because .NET Standard is not executable and cannot be run on its own. The solution is either of the following.
Option 1. Replace the project using Class Library (.NET Class) and start over the steps above. That’s it!
Option 2. Set the executable project as a starting project and run Scaffold-DbContext command from a class library. Here is how.
Option 2-1. Add an exexutable app and reference your class library
Option 2-2. Install Microsoft.EntityFrameworkCore.Design in an executable app
(ex AdventureWorks.App)
Install-Package Microsoft.EntityFrameworkCore.Design
Option 2-3. Set Startup Project as your executable app
(ex AdventureWorks.App)
Option 2-4. Run Scaffold-DbContext command. Make sure Package Manager Console is pointed to your class library.
(ex AdventureWorks.Ef)
Now you should have all the models and context generated!