Edit

Part 2, add a model to a Razor Pages app in ASP.NET Core

In this tutorial, you add classes for managing movies in a database. The app's model classes use Entity Framework Core (EF Core) to work with the database. EF Core is an object-relational mapper (O/RM) that simplifies data access. You write the model classes first, and EF Core creates the database.

The model classes are known as POCO classes (from "Plain-Old CLR Objects") because they don't have a dependency on EF Core. They define the properties of the data that are stored in the database.

Add a data model

  1. In Solution Explorer, right-click the RazorPagesMovie project. Select Add > New Folder. Name the folder Models.

  2. Right-click the Models folder. Select Add > Class. Name the class Movie.

  3. Add the following properties to the Movie class:

    using System.ComponentModel.DataAnnotations;
    
    namespace RazorPagesMovie.Models;
    
    public class Movie
    {
        public int Id { get; set; }
        public string? Title { get; set; }
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string? Genre { get; set; }
        public decimal Price { get; set; }
    }
    

The Movie class contains:

  • The ID field is required by the database for the primary key.

  • A [DataType] attribute that specifies the type of data in the ReleaseDate property. By using this attribute:

    • The user isn't required to enter time information in the date field.
    • Only the date is displayed, without any time information.
  • A question mark after string indicates that the property is nullable. For more information, see Nullable reference types.

DataAnnotations are covered in a later tutorial.

Build the project to verify there are no compilation errors.

Scaffold the movie model

In this section, you scaffold the movie model. The scaffolding tool generates pages for Create, Read, Update, and Delete (CRUD) operations for the movie model.

  1. Right-click on the Pages folder. Select Add > New Scaffolded Item.

New Scaffolded Item.

  1. In the Add New Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.

Add Scaffold.

  1. Complete the Add Razor Pages using Entity Framework (CRUD) dialog:

    1. In the Model class drop down, select Movie (RazorPagesMovie.Models).
    2. In the Data context class row, select the + (plus) sign.
      1. In the Add Data Context dialog, the class name RazorPagesMovie.Data.RazorPagesMovieContext is generated.
      2. In the Database provider drop down, select SQL Server.
    3. Select Add.

    Add Razor Pages.

The appsettings.json file is updated with the connection string used to connect to a local database.

Warning

This article uses a local database that doesn't require the user to be authenticated. Production apps should use the most secure authentication flow available. For more information on authentication for deployed test and production apps, see Secure authentication flows.

Files created and updated

The scaffold process creates the following files:

  • Pages/MoviePages: Create, Delete, Details, Edit, and Index.
  • RazorPagesMovieContext.cs

The next tutorial explains the created files.

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

using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.");

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

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapStaticAssets();
app.MapRazorPages()
   .WithStaticAssets();

app.Run();

Later in this tutorial, you learn about the Program.cs changes.

Create the initial database schema by using EF's migration feature

The migrations feature in Entity Framework Core provides a way to:

  • Create the initial database schema.
  • Incrementally update the database schema to keep it in sync with the app's data model. This approach preserves existing data in the database.

In this section, use the Package Manager Console (PMC) window to:

  • Add an initial migration.

  • Update the database with the initial migration.

  • From the Tools menu, select NuGet Package Manager > Package Manager Console.

    PMC menu.

  • In the PMC, enter the following command:

    Add-Migration InitialCreate
    
  • The Add-Migration command generates code to create the initial database schema. The schema is based on the model specified in DbContext. The InitialCreate argument names the migration. You can use any name, but by convention choose a name that describes the migration.

The following warning is displayed, which you address in a later step:

No store type was specified for the decimal column 'Price' on entity type 'Movie'. This condition causes values to be silently truncated if they don't fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values in 'OnModelCreating' by using 'HasColumnType', specify precision and scale using 'HasPrecision', or configure a value converter using 'HasConversion'.

  • In the PMC, enter the following command:

    Update-Database
    

    The Update-Database command runs the Up method in migrations that aren't applied. In this case, the command runs the Up method in the Migrations/<time-stamp>_InitialCreate.cs file, which creates the database.

The data context RazorPagesMovieContext:

  • Derives from Microsoft.EntityFrameworkCore.DbContext.
  • Specifies which entities are included in the data model.
  • Coordinates EF Core functionality, such as Create, Read, Update, and Delete, for the Movie model.

The RazorPagesMovieContext class in the generated file RazorPagesMovieContext.cs:

using Microsoft.EntityFrameworkCore;

public class RazorPagesMovieContext(DbContextOptions<RazorPagesMovieContext> options) : DbContext(options)
{
    public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; } = default!;
}

The preceding code creates a DbSet<Movie> property for the entity set. In Entity Framework terminology, an entity set typically corresponds to a database table. An entity corresponds to a row in the table.

The name of the connection string is passed to the context by calling a method on a DbContextOptions object. For local development, the Configuration system reads the connection string from the appsettings.json file.

Test the app

  1. Run the app and append /MoviePages to the URL in the browser (http://localhost:{PORT}/MoviePages, where the {PORT} placeholder is the port).

    If you receive the following error:

    SqlException: Cannot open database "RazorPagesMovieContext-GUID" requested by the login. The login failed.
    Login failed for user 'User-name'.
    

    You missed the migrations step.

  2. Test the Create New link.

Create page.

Note

You might not be able to enter decimal commas in the Price field. To support jQuery validation for non-English locales that use a comma (",") for a decimal point and for non US-English date formats, the app must be globalized. For globalization instructions, see this GitHub issue.

  1. Test the Edit, Details, and Delete links.

The next tutorial explains the files created by scaffolding.

Examine the context registered with dependency injection

ASP.NET Core is built with dependency injection. Register services, such as the EF Core database context, with dependency injection during application startup. Provide components that require these services (such as Razor Pages) via constructor parameters. The constructor code that gets a database context instance is shown later in the tutorial.

The scaffolding tool automatically creates a database context and registers it with the dependency injection container. The following highlighted code is added to the Program.cs file by the scaffolder:

using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.");

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

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapStaticAssets();
app.MapRazorPages()
   .WithStaticAssets();

app.Run();

Troubleshooting with the completed sample

If you run into a problem you can't resolve, compare your code to the completed project. View or download completed project (how to download).

Next steps