Database First Approach Example - Entity Framework Core Framework

Database First Approach Example - Entity Framework Core Framework

The Database First approach is suitable when the database schema is already defined or when there is an existing database that needs to be integrated into the application. It allows developers to focus on application logic without worrying about database design and SQL queries, as much of the database interaction is handled through the generated entity classes and ORM frameworks.

To get started with Database First Approach follow the following steps:

  1. Open Visual Studio and click on create a new project from the right helper menu.

    1. Choose ASP.NET Core Web App (Model-View-Controller)

    2. Provide the appropriate name for the project and click on Next and click on Create.

    3. Let's install the necessary packages now. Right-click on the dependencies from Solution Explorer and select Manage NuGet Packages

    4. Install following packages

    5. Microsoft.EntityFrameworkCore.Design

      Microsoft.EntityFrameworkCore.Design contains all the design-time logic for Entity Framework Core. It's the code that all of the various tools (PMC cmdlets like Add-Migration, dotnet ef & ef.exe) call into.

    6. Microsoft.EntityFrameworkCore.Tools

      Enables these commonly used commands: Add-Migration Bundle-Migration Drop-Database Get-DbContext Get-Migration Optimize-DbContext Remove-Migration Scaffold-DbContext Script-Migration Update-Database

    7. Microsoft.EntityFrameworkCore.SqlServer

      Microsoft SQL Server database provider for Entity Framework Core.

    8. Now let's create a models class and DB context using the scaffold command

      I already have a database on the server running and I am using the database that we have created on Code First Approach.

      1. Goto Tools and select NuGet Package Manager and select NuGet Package Manager.

        On the package manager console, enter the commands:

         Scaffold-DbContext "Server=(localdb)\MSSQLLocalDB;database=CodeFirst4;trusted_connection=true" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
        

Note: If Scaffold-DbContext is not found error then install in the package manager console

    Install-Package Microsoft.EntityFrameworkCore.Tools
  1. Now you will see your model class and db context is generated for you from the database

    1. If you want to update the models class once the database schema has been changed. Run this command

       Scaffold-DbContext "Server=(localdb)\MSSQLLocalDB;database=CodeFirst4;trusted_connection=true"Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -force
      
    2. Now update your connection string in appsettings.json file and Program.cs file as:

       "ConnectionStrings": {
         "dbcs": "Data Source=(localdb)\\MSSQLLocalDB; Database=CodeFirst; Initial Catalog=CodeFirst;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
       },
      
      var builder = WebApplication.CreateBuilder(args);
      
      // Add services to the container.
      builder.Services.AddControllersWithViews();
      
      var provider = builder.Services.BuildServiceProvider();
      var config = provider.GetRequiredService<IConfiguration>();
      builder.Services.AddDbContext<StudentDBContext>(item => item.UseSqlServer(config.GetConnectionString("dbcs")));
      
      var app = builder.Build()
      

      To create the news continue with tutorials on the code-first approach link

    3. Wait Wait, if you want to generate a controller and methods for the database there is a quicker way.

      1. Delete a previous controller eg: HomeController.cs

      2. Add a new controller to your controller folder and select MVC Controller with views using the Entity Framework option.

      3. Choose a model class to generate views for and click on add as

      4. A scaffold will be generated for your model class, this might take some moments.

        As a result, all the views for students are updated.

Did you find this article valuable?

Support Sudip Bhandari by becoming a sponsor. Any amount is appreciated!