Reverse Engineering(Scaffolding) in Entity Framework Core Using ASP.Net Core Web API

 As we know, EF Core does not support a visual designer for the DB model and wizard to create the entity and context classes. So, we need to do Reverse engineering, which is the process of scaffolding entity type classes and a DbContext class based on a database schema. This reverse engineering command creates entity and context classes (by deriving DbContext) based on the schema of the existing database. It also includes the relationships(i.e. foreign key, primary key) between the entities.

It can be performed using the Scaffold-DbContext command of the EF Core Package Manager Console (PMC) tools or the dotnet ef DBContext scaffold command of the .NET Command-line Interface (CLI) tools.

The command for Scaffold:

Scaffold-DbContext -StartupProject 'Startup Project Name' -Project 'Project Name for generating entities'
-Connection Name='Connection string name'
Microsoft.EntityFrameworkCore.SqlServer
-OutputDir 'Folder Name where the entities will store'
-Context 'Context File Name'
-Force -DataAnnotation -UseDatabaseNames

Let's Start with an Example:

First, create an ASP.Net core web application named 'EmployeeApp'. Then open your appsettings.json file and add your connection string inside the 'ConnectionStrings' Section.

Install 3 Nuget Packages in ASP.Net Core Web API Project.

1. Microsoft.EntityFrameworkCore, Version="5.0.17"
2. Microsoft.EntityFrameworkCore.SqlServer, Version="5.0.17"
3. Microsoft.EntityFrameworkCore.Tools, Version="5.0.17"


Then add another Class Library Project inside the Same Solution, naming it 'DataAccess'. Create a Folder 'DBModel' inside the 'DataAccess' Project.

Install 2 Nuget Packages in DataAccess Project,

1. Microsoft.EntityFrameworkCore, Version="5.0.17"
2. Microsoft.EntityFrameworkCore.SqlServer, Version="5.0.17"

Now Add the 'AppDBContext.cs' class file. Please refer following code.

Let's go to StartUp.cs file, Add the following code,


After that open the package manager console. Tools->Nuget Package Manager-> Package Manager Console.

Write the following command and click on Enter.

Scaffold-DbContext -StartupProject EmployeeApp -Project DataAccess -Connection Name=DefaultConnection Microsoft.EntityFrameworkCore.SqlServer -OutputDir DBModel -Context AppDBContext -Force -DataAnnotation -UseDatabaseNames

Now we can see the Entities are generated inside the DBModel folder of the DataAccess Project.


For more details, please refer to this video link,


 





Post a Comment

0 Comments