Scaffold-dbcontext Strings for Database-First in .NET Core

Introduction

When working with Entity Framework Core in ASP.NET Core applications, generating DbContext and models is a crucial step. In this blog post, we'll explore three methods to simplify this process: using scaffolding commands, adhering to standard practices, and leveraging EF Core Power Tools in Visual Studio.
In this guide, we'll delve into the following three approaches to facilitate DbContext and model generation:

  1. Scaffolding Command in the console.
  2. Using standard methods.
  3. Utilizing EF Core Power Tools.

Method 1. Scaffolding Command

Step 1. Execute scaffolding command in Tools -- > NuGet Package Manager -- > Package Manager Console.

Step 2. Add the connection string directly.

scaffold-dbcontext -provider Microsoft.EntityFrameworkCore.SqlServer -connection "Data Source=(Server);Initial Catalog=(Database Name);UserId=(Username);Password=(Password);TrustServerCertificate=true;"  -OutputDir Models

Step 3. Scaffold DbContext and models using the Scaffold-DbContext command.

Method 2. Standard Practices

Step 1. Add connection string in app.settings.json.

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(Server Name);Initial Catalog=(Database Name);user id=(Username for connection on db);password=(Password);TrustServerCertificate=True;"
  }
}

Step 2. Manually create a DbContext file. The class name should be ("DatabaseName"+Context.cs).
  

  • NuGet Packages  Required
    • Microsoft.EntityFrameworkCore
    • Microsoft.EntityFrameworkCore.SqlServe
    • Microsoft.EntityFrameworkCore.Tools
using Microsoft.EntityFrameworkCore;

namespace BackEnd.Models //solution name models
{

    //**The class name should be ("DatabaseName"+Context.cs)**
    // database name  = TryDbApproch. 
    // class name  = TryDbApprochContext.cs.

    public class TryDbApprochContext : DbContext   
    {
        public TryDbApprochContext(DbContextOptions<TryDbApprochContext> options)
            : base(options)
        {
        }
    
}

Step 3. Configure DbContext and connection string in program.cs.

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<TryDbApprochContext>(options =>
        options.UseSqlServer(connectionString));

or

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<TryDbApprochContext>(options => options.UseSqlServer(connectionString, serverOptions =>
{
    serverOptions.EnableRetryOnFailure(
        maxRetryCount: 3,       // Maximum number of retry attempts
        maxRetryDelay: TimeSpan.FromSeconds(30), // Maximum delay between retries
        errorNumbersToAdd: null); // Specific error numbers to retry on (null retries on all transient errors)
}));

Step 4. Scaffold DbContext and models using the Scaffold-DbContext command.


Scaffold-DbContext "Name=DefaultConnection" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -f             

Step 5. Paste the Scaffold string in the Tools -- > NuGet Package Manager -- > Package Manager Console. To generate models and DbContext files for the project.

Method 3. EF Core Power Tools

Reverse Engineer acts like Entity Data Model, where it generates the tables of our database as Entity Classes in the code and also Db Context class based upon our Database.

Step 1. Install EF Core Power Tools extension in Visual Studio. Path = "Extension --> Manage Extensions... --> Search == EF Core Power Tools -->  Install ".

Step 2. Right-click on Project. There, you will find an option installed, EF Core Power Tools.

Click on Reverse Engineer there you will find the Db Connection Option.

 Ef Power Tools

Step 3. Click on Add to connect with the Database Server.

Choose database connections

Step 4. Test the connection with the SQL server.

  • Provide the SQL Server name in the Text Box and find whether you are using Windows or SQL Authentication.
  • Select the Database Under the Select or enter the database. 
  • Click on Test Connection to check where the connection is configured in a proper way.
  • Click on OK.
    Test connection

Step 5. That's done! The Connection with the database will show in the selected DropDown  -> Click on OK.

Database connection

Step 6. Select the Tables which you want to include in your project and click on OK.

Select table to script

Step 7. By default, it will add the DB name as the Context name, which you can change if you want and also it will select Entitytypes & DbContext by default.

Step 8. You will get a confirmation, as shown below. Press "OK".

Microsoft Visual Studio

Step 9. Finally. The model Classes with Db Context have been generated automatically. This is how simple it is to work with EF Core Power Tools.

Conclusion

Generating DbContext and models in Entity Framework Core doesn't have to be complex. By following these methods, you can streamline your development process and focus more on building your application logic rather than dealing with database configurations.