How to reverse engineer a database with Entity Framework Core

Here are the steps to reverse engineer or scaffold your SQL Server database into C# models.

Here are the steps to reverse engineer or scaffold your SQL Server database into C# models.

Code first or database first are generally the two paths forward when I'm staring a new project. Generally I like to create the models in code first and then do a database migration to create the database. That's considered a code first approach. However, when I'm work with larger organizations there tends to be a database person who takes care of creating the database, tables, views and relationships. When this is the case, I will refer to a database first approach. In the database first approach I use reverse engineering to scaffold the database using Entity Framework which allows you to generate entity classes and a DbContext class based on an existing database schema.

Here’s how you do it:

Prerequisites

  1. Install Entity Framework Core Tools: Install the necessary EF Core tools.

Step 1: Install EF Core Tools

First, install the EF Core tools. You can do this using the .NET CLI or the NuGet Package Manager in Visual Studio.

Using .NET CLI:

Run the following command in your project directory to install the EF Core CLI tools:

dotnet tool install --global dotnet-ef

Next, install the necessary EF Core packages in your project. For example, if you are using SQL Server, you would install the SQL Server provider:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design

Step 2: Scaffold the Database

Use the dotnet ef dbcontext scaffold command to reverse engineer your database. You need to provide the connection string to your database and the provider to use. Use the option --force to overwrite any classes or models inside the output folder.

dotnet ef dbcontext scaffold "Server=your_server;Database=your_database;User Id=your_user;Password=your_password;" Microsoft.EntityFrameworkCore.SqlServer -o Models --force

That's it. Running the above command will output the database in C# model form into the Models folder of your project.