Entity Framework scaffold-dbcontext Commands with example in .NET

EFCore Scaffold DbContext Commands in NET Core Entity Framework scaffold dbcontext Commands with example in NET

In this article, we shall see step-by-step details on various useful Entity Framework (EFCore) scaffold-dbcontext Commands examples.

We shall try covering the below aspects overall in this article,

What is Scaffold-DbContext

Scaffold-DbContext” is a command provided by Entity Framework Core (EF Core), an Object-Relational Mapping (ORM) framework for .NET applications.

It’s a tool that can be used to automatically create the necessary C# classes (entity classes) and a DbContext class to represent the database tables and relationships after reverse-engineering a database schema.

“Scaffold-DbContext” can be used to quickly construct the entity classes and DbContext when working with an existing database in your.NET application using EF Core.

You can avoid writing these classes manually and are guaranteed that the table names, columns, and relationships in the C# classes match those in the database.

It decreases the amount of code written manually and maintenance required for data-oriented applications.

This concept works best with the Database First or Schema First approach very well.

Before starting please make sure the required tools are installed properly.

How to Install Entity Framework – EFCore Scaffold-DbContext

Below tools required,

  • Using Scaffold-DbContext (Using PMC for project-specific )

  • Using dotnet ef dbcontext scaffold ( Global support for all EFCore projects)

The above-listed tools can be used with Visual Studio or VS Code.

Setting up EFCore using EntityFrameworkCore.Tools nuget package

EFCore Package Manager Console Tool can be installed by using the below NuGet package within the project directory,

PM> Install-Package Microsoft.EntityFrameworkCore.Tools

Scaffold DbContext using EFCore PMCPackage Manager Console Tool Entity Framework scaffold dbcontext Commands with example in NET

If you would like to verify installed EF Core tools please run the below command

PM> Get-Help about_EntityFrameworkCore

Scaffold DbContext Drop Database Update Database 1 Entity Framework scaffold dbcontext Commands with example in NET

Setting up EFCore CLI Global Tool

If not using Visual Studio as an IDE then you can create, scaffolding globally using

EFCore CLI Tool can be installed by using global dotnet-ef tools.

The CLI tools are cross-platform and easy to use.

Run the below command on the Command Prompt,

dotnet tool install --global dotnet-ef

Example:

dotnet tool install global dotnet ef Entity Framework scaffold dbcontext Commands with example in NET

Followed by adding the below Microsoft.EntityFrameworkCore.

Design package using CLI or Visual Studio IDE (Please use the project location directory to run this command)

Example:

 dotnet add package Microsoft.EntityFrameworkCore.Design 

How to verify the Entity framework version

Once installed successfully, please verify the installation by running the below command,

dotnet ef 

Scaffold DbContext Drop Database Update Database command net core31 1 Entity Framework scaffold dbcontext Commands with example in NET

You are all set !!

Please run the scaffold-dbcontext command to generate the required scaffolding as explained above.

So far above we only looked at how to set up the EFCore tools.

Let’s now see how to generate the code using scaffolding commands.

scaffold-dbcontext Commands

By default, if in the commands, you don’t specify any Table properties then scaffolding will be done at the Database level.

In such scenarios, all the Tables will be scaffolded (even if it is not required).

Command :

PM>Scaffold-DbContext "your DB connection string" Microsoft.EntityFrameworkCore.SqlServer 

Or using the global CLI tool,

Command

dotnet ef dbcontext scaffold "your DB connection string" Microsoft.EntityFrameworkCore.SqlServer 

Example:

PM> Scaffold-DbContext "Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir Context -Context EmployeeContext

The above commands will create scaffolding on the given database.

All the model entities will be created in the Models directory and the Context name will be “EmployeeContext

Scaffolding using Scaffold-DbContext for one Table

Command :

PM> Scaffold-DbContext -Tables [TableName]

Or using a global CLI tool

 dotnet ef dbcontext scaffold -table [TableName] 

Example:

PM>Scaffold-DbContext "Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Tables "Employee" -OutputDir Models -ContextDir Context -Context EmployeeContext 

Scaffold DbContext select tables to scaffold command Entity Framework scaffold dbcontext Commands with example in NET

The above command will create a scaffold for only a single table from the database.

Scaffolding Scaffold-DbContext Multiple Tables(Selected)

Command:

 PM> scaffold-dbcontext -Tables Table1, Table2, Table3

OR

dotnet ef dbcontext scaffold -table Employee,Contractor, Vendor

Example:

PM>Scaffold-DbContext Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -Tables Employee, Contractor, Vendor  -OutputDir Models -ContextDir Context -Context EmployeeContext 

The above command will create scaffolding for Tables specified within the command i.e Table1, Table2, and Table3.

Create Scaffolding using Schema

You can scaffold using Schema as well. Please use the below command.

 PM> Scaffold-DbContext -Schema <schema> 

Naming conventions for Table and Entities

Please note that Table and Column names will follow the .NET naming conventions for Types and properties by default i.e. Scaffolding will generate names on its own.

If you would like to use the same naming convention as defined by your database and database schema please use the additional command with UseDatabaseNames while scaffolding.

With UseDatabaseNames EFCore will try its best to respect the existing convention based on Table and schema structure and for any elements causing the issue, it will use default conventions.

Command:

PM> Scaffold-DbContext -UseDatabaseNames 

OR

 dotnet ef dbcontext scaffold --use-database-names 

Fluent API or Data Annotations

All scaffolding of Entity types will be configured using the Fluent API by default.

If you would like to use Data annotations please specify the below commands to generate scaffolding accordingly.

Command

   PM> Scaffold-DbContext -DataAnnotations 

OR

  dotnet ef dbcontext scaffold --data-annotations  

Naming Conventions for Context and Directories

DBContext Name:

DbContext class name will be the name of the database by default.

It will be suffixed with Context.

To specify a custom name use below additional command below,

Command

PM> Scaffold-DbContext  -Context [ContetName]

OR

    dotnet ef dbcontext scaffold --context 

Model and Directory folder naming

  • By default Entity model classes and DbContext class will be scaffolded into the project’s root directory.

  • By default, the ‘Context’ folder will be used to store Context classes and the ‘Models folder will be used to store model classes.

Custom Context Folder

If you want to provide a Custom Context Folder use the below command,

Command

 PM>Scaffold-DbContext -ContextDir EmployeeContext

OR

 dotnet ef dbcontext scaffold --context-dir EmployeeContext 

Custom Model Folder

If you want to provide Custom Model Folder use the below command.

Command

 PM>Scaffold-DbContext -OutputDir EmployeeContextModels

OR

dotnet ef dbcontext scaffold --output-dir EmployeeContextModels

Scaffolding with Overwriting – Scaffold-DbContext

If you already have scaffolding and want to override existing files with new scaffolding (generated using new or updated schema) please use the below command.

Command

 PM>Scaffold-DbContext -Force 

Or

  dotnet ef dbcontext scaffold --force

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

Today in this article we looked at the EFCore Scaffolding feature which helps us in reverse engineering entity type classes.

We looked at various useful scaffold-dbcontext commands to work with your database schema.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



4 thoughts on “Entity Framework scaffold-dbcontext Commands with example in .NET”

  1. It would be nice for Scaffold to be able to work WITHOUT a build first. My project with the DBContext in it refers to a .net 4.7 project. Because of this MSBuild won’t work whether in standard or VS command line as it cant use the Task ResolveComReference to act on the included project. This means that to be able to do any of the scaffolding tasks I have to un-link the 4.7 project and remove any references to it (rather a major task). This means that I am practically required to manually code any changes I want in either direction with is a major PITA.

    1. Hello Allan. Thanks for your comments and for sharing the details of the issue mentioned. Agree. I observed that as a current limitation for scaffold commands need any compile time issues to be resolved upfront. If your build is good scaffolding just works fine. You may try another alternative (maybe it will be a big task) like migrating 4.7 projects to the standard library or Net core library if possible. However, Please do share your solution here in the below comments if you happen to figure it near future..

  2. Stored procedure are not generate scaffold dbconext model automatically like EF6.
    Stored procedures are missing from below code.

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    modelBuilder.Entity(entity =>
    {
    entity.Property(e => e.CustomerCode)
    .HasMaxLength(50)
    .IsUnicode(false);

    entity.Property(e => e.CustomerName)
    .HasMaxLength(50)
    .IsUnicode(false);
    });

    modelBuilder.Entity(entity =>
    {
    entity.Property(e => e.VendorName)
    .HasMaxLength(20)
    .IsUnicode(false);
    });

    OnModelCreatingPartial(modelBuilder);
    }

    1. Hi Rasmita- ES6 with EDMX file had SP supported feature but unfortunately .NET Core as of now doesn’t support it.

      However, it supports calling the stored procedure using FromSql from EFCore directly

      var blogs = context.Blogs
      .FromSql(“EXECUTE dbo.GetTheCodeBuzzArticles”)
      .ToList();

      For more details – please read through this article Stored Procedure in Entity Framework Core – Guidelines

Leave a Comment

Your email address will not be published. Required fields are marked *