Note: this article is published on 07/21/2024.

After I wrote several articles on this site, I found out it seemed almost for every article, I needed to set up a sample application associated with an entity framework if accessing the database. And, every time, I needed to rewrite the setup process from scratch in order for a new reader to follow along easily. Even for introducing a very simple concept, such as Caching, I needed to spend 80% of the time setting up the sample app, and only 20% on introducing the Caching concept itself.

Therefore, I think it is better to write a basic model such as entity framework sample for various approaches, and then I can reuse them when needed. I made a list of the series of articles below, I will write them one by one, while the Entity framework overview and concept will be covered in the article (0):

Note

We write the Entity Framework for MVC module, but the pattern is the same or similar when applying to Web Application or Web API.

Introduction

This article is about Entity Framework with .Net Core Razor Pages Code-First approach. I will have a brief introductions on Razor (syntax) and Razor Pages.

This article will have the same structure with, such as

They have a lot of similar features. We try to emphasize the differences. However, in order for reader to have a consistent reading, we will keep the similar ones as is. This article will based on this Microsoft Tutorial: Get started with Razor Pages in ASP.NET Core | Microsoft Learn.

We will make a sample app step by step,

At the end, we will have an .Net Core Razor Pages that can consume a database directly through entity framework.

Step 1 - Create a .Net Core Razor Page app

We use the current version of Visual Studio 2022 17.10.3 and .NET Core 8.0 to build the app:

Note

  1. In the Additional Information Page, do not select Enable container support. if you do, you might get this kind of error,
    • Platform not supported exception localdb is not supported on this platforms
      • that is probably required to use linux container to held the database.
  2. For details, you may reference here.

Build and run the app, you will see the following image showing the app,

Step 2 - Add a Data Model

Add a data model, an entity class, into the app, with name as Movie:

The Movie class contains:

Step 3 - Scaffold the Movie Model (Set up DbContext and Data Connection)

This step is different from the previous, both

for them, we needed to add DbContext and Data Connection code manually, then did the Scaffolding. Now, we go to scaffolding directly after setup the data model:

From Solution Explorer:

Files created and updated

The scaffold process creates the following files:

Noted the difference between Razor pages and MVC module: MVC creates controller to handle the code while Razor pages create code behind .cshtml.cs files to handle the logic.

The scaffold process adds the following highlighted code to the Program.cs file:

that registers the database connection context, RazorPagesMovieContext class:

builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

Note

As in .Net Framework MVC, you don't actually need to add connection string manually, even no need for DbContext, Entity Framework will create a LocalDB database in the users directory with the fully qualified name of the DbContext class.

Remember for the previous .Net Core version, say, 5.0, you have to create a DbContext manually in code, and add a connection string in the appsettings.json file and have to register it in Startup file. Otherwise, it will not work.

Step 4 - Migrate and Update database

This is the same as .Net Core 5.0, you have to Migrate and Update database before to make the app work.

Click "Tools->NuGet Package Manager->Package Manager Console", and run the PMC command

Add-Migration InitialCreate

Two files created under Migration folder:

Run PMC command,

update-database 

Examine the database, before running the command:

After, the database RazorPagesMovieContext-.... is created:

Tables created:

Seed the database

Create a new class named SeedData in the Models folder with the following code:

using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;

namespace RazorPagesMovie.Models;

public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new RazorPagesMovieContext(
            serviceProvider.GetRequiredService<
                DbContextOptions<RazorPagesMovieContext>>()))
        {
            if (context == null || context.Movie == null)
            {
                throw new ArgumentNullException("Null RazorPagesMovieContext");
            }

            // Look for any movies.
            if (context.Movie.Any())
            {
                return;   // DB has been seeded
            }

            context.Movie.AddRange(
                new Movie
                {
                    Title = "When Harry Met Sally",
                    ReleaseDate = DateTime.Parse("1989-2-12"),
                    Genre = "Romantic Comedy",
                    Price = 7.99M
                },

                new Movie
                {
                    Title = "Ghostbusters ",
                    ReleaseDate = DateTime.Parse("1984-3-13"),
                    Genre = "Comedy",
                    Price = 8.99M
                },

                new Movie
                {
                    Title = "Ghostbusters 2",
                    ReleaseDate = DateTime.Parse("1986-2-23"),
                    Genre = "Comedy",
                    Price = 9.99M
                },

                new Movie
                {
                    Title = "Rio Bravo",
                    ReleaseDate = DateTime.Parse("1959-4-15"),
                    Genre = "Western",
                    Price = 3.99M
                }
            );
            context.SaveChanges();
        }
    }
}

If there are any movies in the database, the seed initializer returns and no movies are added.

Add the seed initializer into program.cs page:

using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;
using RazorPagesMovie.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    SeedData.Initialize(services);
}

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

such as

Step 5 - Run the App and Test

Setup the link in main page:

For convenience, you can update one line code in file Pages/Shared/_Layout.chtml, replace /index:

to /Movies/Index

Run the App, the final result will be:

Summary

The .NET Core Razor Pages module for Code-First approach is very similar to the MVC module and the .Net Core MVC Module, except something new

  1. No need to setup DbContext and Connection String manually, no need to register DbContext to Framework, all of them are auto done by Scaffolding
  2. Need to Migrate and Update database.

Comparing Razor with MVC, Core MVC modules, Razor is simply divide the long code first approach into thre major steps:

  1. Modle to set up front end data entity
  2. Scaffolding to setup front end code;
  3. PMC command to handle data migration and update.

Razor Pages:

MVC module:

.Net Core MVC Module:

Reference