aspnetcore/tutorials/razor-pages/model/includes/model5.md
:::moniker range="= aspnetcore-5.0"
<!-- In the next update on the CLI version, let the scaffolder do the same work the VS driven scaffolder does. That is, create the DB context, etc -->In this section, 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.
View or download sample code (how to download).
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.
[DataType(DataType.Date)]: The [DataType] attribute specifies the type of the data (Date). With this attribute:
Models.Models folder named Movie.cs.Add the following properties to the Movie class:
The Movie class contains:
The ID field is required by the database for the primary key.
[DataType(DataType.Date)]: The [DataType] attribute specifies the type of the data (Date). With this attribute:
<a name="dc"></a>
In the Solution Tool Window, control-click the RazorPagesMovie project, and then select Add > New Folder.... Name the folder Models.
Control-click the Models folder, and then select Add > New File....
In the New File dialog:
Add the following properties to the Movie class:
The Movie class contains:
The ID field is required by the database for the primary key.
[DataType(DataType.Date)]: The [DataType] attribute specifies the type of the data (Date). With this attribute:
DataAnnotations are covered in a later tutorial.
Build the project to 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 a Pages/Movies folder:
Right-click on the Pages/Movies folder > Add > New Scaffolded Item.
In the Add 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, Startup.cs, and .csproj files. Run the following command:
dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages/Movies --referenceScriptLibraries -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. |
-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.
Create a Pages/Movies folder:
Control-click on the Pages/Movies folder > Add > New Scaffolding....
In the New Scaffolding dialog, select Razor Pages using Entity Framework (CRUD) > Next.
Complete the Add Razor Pages using Entity Framework (CRUD) dialog:
RazorPagesMovie.Data.RazorPagesMovieContext.The appsettings.json file is updated with the connection string used to connect to a local database.
[!INCLUDE managed-identities-test-non-production]
The scaffold process creates the following files:
Data/RazorPagesMovieContext.csStartup.csThe created and updated files are explained in the next section.
<a name="pmc"></a>
The migrations feature in Entity Framework Core provides a way to:
In this section, the Package Manager Console (PMC) window is used to:
From the Tools menu, select NuGet Package Manager > Package Manager Console.
In the PMC, enter the following commands:
Add-Migration InitialCreate
Update-Database
Run the following .NET CLI commands:
dotnet ef migrations add InitialCreate
dotnet ef database update
[!NOTE] For SQLite, column type for the
Pricefield is set toTEXT. This is resolved in a later step.
For SQL Server, the preceding commands generate the following warning: "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()'."
Ignore the warning, as it will be addressed in a later step.
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.
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.
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.
Examine the Startup.ConfigureServices method. The highlighted line was added by the scaffolder:
The RazorPagesMovieContext coordinates EF Core functionality, such as Create, Read, Update and Delete, for the Movie model. The data context (RazorPagesMovieContext) is derived from Microsoft.EntityFrameworkCore.DbContext. The data context specifies which entities are included in the data 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.
Examine the Up method.
<a name="test"></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 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.
[!INCLUDEs]
The next tutorial explains the files created by scaffolding.
[!div class="step-by-step"] Previous: Get Started Next: Scaffolded Razor Pages
:::moniker-end