aspnetcore/tutorials/razor-pages/model/includes/model8.md
:::moniker range="= aspnetcore-8.0"
In this tutorial, classes are added 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.
In Solution Explorer, right-click the RazorPagesMovie project > Add > New Folder. Name the folder Models.
Right-click the Models folder. Select Add > Class. Name the class Movie.
Add the following properties to the Movie class:
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. With this attribute:
The 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.
Models.Models folder named Movie.cs.Add the following properties to the Movie class:
The Movie class contains:
An ID field to provide a primary key for the database.
A [DataType] attribute to specify the type of data in the ReleaseDate field. With this attribute:
The question mark after string indicates that the property is nullable. For more information, see Nullable reference types.
DataAnnotations are covered in a later tutorial.
<a name="dc7"></a>
In Visual Studio Code, press <kbd>Ctrl</kbd>+<kbd>F5</kbd> to run the app without debugging.
In the Panel below the editor region, select the PROBLEMS tab, or from the View menu, select Problems if it is not currently in view. Verify there are no compilation errors.
In this section, the movie model is scaffolded. That is, the scaffolding tool produces pages for Create, Read, Update, and Delete (CRUD) operations for the movie model.
Create the Pages/Movies folder:
Right-click on the Pages/Movies folder > Add > New Scaffolded Item.
In the Add New Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.
Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
RazorPagesMovie.Data.RazorPagesMovieContext is generated.The appsettings.json file is updated with the connection string used to connect to a local database.
Open a command shell to the project directory, which contains the Program.cs and .csproj files. Run the following command:
dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovie.Data.RazorPagesMovieContext -udl -outDir Pages/Movies --referenceScriptLibraries --databaseProvider sqlite
<a name="codegenerator"></a> The following table details the ASP.NET Core code generator options.
| Option | Description |
|---|---|
-m | The name of the model. |
-dc | The DbContext class to use including namespace. |
-udl | Use the default layout. |
-outDir | The relative output folder path to create the views. |
--referenceScriptLibraries | Adds _ValidationScriptsPartial to Edit and Create pages |
Use the -h option to get help on the dotnet aspnet-codegenerator razorpage command:
dotnet aspnet-codegenerator razorpage -h
For more information, see dotnet aspnet-codegenerator.
[!INCLUDE managed-identities-test-non-production]
The scaffold process creates the following files:
Data/RazorPagesMovieContext.csThe created files are explained in the next tutorial.
The scaffold process adds the following highlighted code to the Program.cs file:
The Program.cs changes are explained later in this tutorial.
<a name="pmc7"></a>
The migrations feature in Entity Framework Core provides a way to:
In this section, the Package Manager Console (PMC) window is used to:
Add an initial migration.
Update the database with the initial migration.
From the Tools menu, select NuGet Package Manager > Package Manager Console.
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 is used to name the migration. Any name can be used, but by convention a name is selected that describes the migration.
The following warning is displayed, which is addressed in a later step:
No type was specified for the decimal column 'Price' on entity type 'Movie'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()'.
In the PMC, enter the following command:
Update-Database
The Update-Database command runs the Up method in migrations that have not been applied. In this case, the command runs the Up method in the Migrations/<time-stamp>_InitialCreate.cs file, which creates the database.
Right-click the RazorPagesMovie.csproj project, and then select Open in Integrated Terminal.
The Terminal window opens with the command prompt at the project directory, which contains the Program.cs and .csproj files.
Run the following .NET CLI command:
dotnet ef migrations add InitialCreate
The migrations command generates code to create the initial database schema. The schema is based on the model specified in DbContext. The InitialCreate argument is used to name the migrations. Any name can be used, but by convention a name is selected that describes the migration.
Run the following .NET CLI command:
dotnet ef database update
The update command runs the Up method in migrations that have not been applied. In this case, update runs the Up method in the Migrations/<time-stamp>_InitialCreate.cs file, which creates the database.
[!NOTE] For SQLite, column type for the
Pricefield is set toTEXT. This is resolved in a later step.
The data context RazorPagesMovieContext:
Movie model.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 in 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.
<a name="test7"></a>
Run the app and append /Movies to the URL in the browser (http://localhost:port/movies).
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.
Test the Create New link.
[!NOTE] You may not be able to enter decimal commas in the
Pricefield. 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.
Test the Edit, Details, and Delete links.
The next tutorial explains the files created by scaffolding.
ASP.NET Core is built with dependency injection. Services, such as the EF Core database context, are registered with dependency injection during application startup. Components that require these services (such as Razor Pages) are provided via constructor parameters. The constructor code that gets a database context instance is shown later in the tutorial.
The scaffolding tool automatically created a database context and registered it with the dependency injection container. The following highlighted code is added to the Program.cs file by the scaffolder:
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).
[!div class="step-by-step"] Previous: Get Started Next: Scaffolded Razor Pages
:::moniker-end