.Net Core EF Code First from Existing Database

Kagawa
3 min readSep 11, 2020

--

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

Scaffold-DbContext command in Package Manager Console

This is the result.

Generated models/context

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!

Class Library .Net Core

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

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)

Set Startup Project

Option 2-4. Run Scaffold-DbContext command. Make sure Package Manager Console is pointed to your class library.
(ex AdventureWorks.Ef)

Run Scaffold-DbContext from a class library

Now you should have all the models and context generated!

Generated models/context

--

--

Kagawa
Kagawa

Written by Kagawa

C# & JavaScript software engineer.

Responses (1)