Back to Aspnetcore

Visual Studio

aspnetcore/tutorials/razor-pages/model/includes/model3.md

latest16.2 KB
Original Source

:::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. 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.

The model classes are known as POCO classes (from "plain-old CLR objects") because they don't have any 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).

[!INCLUDE managed-identities-test-non-production]

Add a data model

Visual Studio

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:

[!code-csharp]

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:

    • The user is not required to enter time information in the date field.
    • Only the date is displayed, not time information.

DataAnnotations are covered in a later tutorial.

Visual Studio Code

  • Add a folder named Models.
  • Add a class to the Models folder named Movie.cs.

Add the following properties to the Movie class:

[!code-csharp]

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:

    • The user is not required to enter time information in the date field.
    • Only the date is displayed, not time information.

DataAnnotations are covered in a later tutorial.

<a name="dc"></a>

Add NuGet packages and EF tools

[!INCLUDE]

Add a database context class

  • In the RazorPagesMovie project, create a new folder named Data.

  • Add the following RazorPagesMovieContext class to the Data folder:

    [!code-csharp]

The preceding code creates a DbSet property for the entity set. In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table. The code won't compile until dependencies are added in a later step.

<a name="cs"></a>

Add a database connection string

Add a connection string to the appsettings.json file as shown in the following highlighted code:

[!code-json]

<a name="reg"></a>

Register the database context

Add the following using statements at the top of Startup.cs:

csharp
using RazorPagesMovie.Data;
using Microsoft.EntityFrameworkCore;

Register the database context with the dependency injection container in Startup.ConfigureServices.

[!code-csharp]

Visual Studio for Mac

  • In the Solution Tool Window, control-click the RazorPagesMovie project, and then select Add > New Folder.... Name the folder Models.

  • Right-click the Models folder, and then select Add > New File....

  • In the New File dialog:

    • Select General in the left pane.
    • Select Empty Class in the center pane.
    • Name the class Movie and select New.

Add the following properties to the Movie class:

[!code-csharp]

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:

    • The user is not required to enter time information in the date field.
    • Only the date is displayed, not time information.

DataAnnotations are covered in a later tutorial.

Build the project to verify there are no compilation errors.

Scaffold the movie model

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.

Visual Studio

Create a Pages/Movies folder:

  • Right-click on the Pages folder > Add > New Folder.
  • Name the folder Movies.

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:

  • In the Model class drop down, select Movie (RazorPagesMovie.Models).
  • In the Data context class row, select the + (plus) sign and change the generated name from RazorPagesMovie.Models.RazorPagesMovieContext to RazorPagesMovie.Data.RazorPagesMovieContext. This change is not required. It creates the database context class with the correct namespace.
  • Select Add.

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

Visual Studio Code

<!-- Until https://github.com/aspnet/Scaffolding/issues/582 is fixed windows needs backslash or the namespace is namespace RazorPagesMovie.Pages_Movies rather than namespace RazorPagesMovie.Pages.Movies -->
  • Open a command window in the project directory, which contains the Program.cs, Startup.cs, and .csproj files.

  • For Windows: Run the following command:

    dotnetcli
    dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages\Movies --referenceScriptLibraries
    
  • For macOS and Linux: Run the following command:

    dotnetcli
    dotnet aspnet-codegenerator razorpage -m Movie -dc RazorPagesMovieContext -udl -outDir Pages/Movies --referenceScriptLibraries
    

<a name="codegenerator"></a> The following table details the ASP.NET Core code generator options:

OptionDescription
-mThe name of the model.
-dcThe DbContext class to use.
-udlUse the default layout.
-outDirThe relative output folder path to create the views.
--referenceScriptLibrariesAdds _ValidationScriptsPartial to Edit and Create pages

Use the -h option to get help on the dotnet aspnet-codegenerator razorpage command:

dotnetcli
dotnet aspnet-codegenerator razorpage -h

For more information, see dotnet aspnet-codegenerator.

Use SQLite for development, SQL Server for production

When SQLite is selected, the template generated code is ready for development. The following code shows how to inject xref:Microsoft.AspNetCore.Hosting.IWebHostEnvironment into Startup. IWebHostEnvironment is injected so ConfigureServices can use SQLite in development and SQL Server in production.

[!code-csharp]

Visual Studio for Mac

Create a Pages/Movies folder:

  • Right-click on the Pages folder > Add > New Folder.
  • Name the folder Movies.

Right-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:

  • In the Model class drop down, select, or type, Movie (RazorPagesMovie.Models).
  • In the Data context class row, type the name for the new class, RazorPagesMovie.Data.RazorPagesMovieContext. This change is not required. It creates the database context class with the correct namespace.
  • Select Add.

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

Add EF tools

Run the following .NET CLI command:

dotnetcli
dotnet tool install --global dotnet-ef

The preceding command adds the Entity Framework Core Tools for the .NET CLI. For more information, see Entity Framework Core tools reference - .NET CLI.

[!INCLUDE]

Use SQLite for development, SQL Server for production

When SQLite is selected, the template generated code is ready for development. The following code shows how to inject xref:Microsoft.AspNetCore.Hosting.IWebHostEnvironment into Startup. IWebHostEnvironment is injected so ConfigureServices can use SQLite in development and SQL Server in production.

[!code-csharp]


Files created

Visual Studio

The scaffold process creates and updates the following files:

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

Updated

  • Startup.cs

The created and updated files are explained in the next section.

Visual Studio for Mac

The scaffold process creates and updates the following files:

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

Updated

  • Startup.cs

The created and updated files are explained in the next section.

Visual Studio Code

The scaffold process creates the following files:

  • Pages/Movies: Create, Delete, Details, Edit, and Index.

The created files are explained in the next section.


<a name="pmc"></a>

Initial migration

Visual Studio

In this section, the Package Manager Console (PMC) 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 commands:

powershell
Add-Migration InitialCreate
Update-Database

Visual Studio Code / Visual Studio for Mac

[!INCLUDE more information on the CLI for EF Core]

Run the following .NET CLI commands:

dotnetcli
dotnet ef migrations add InitialCreate
dotnet ef database update

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 Migrations/<time-stamp>_InitialCreate.cs file, which creates the database.

Visual Studio

Examine the context registered with dependency injection

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:

[!code-csharp]

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.

[!code-csharp]

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.

Visual Studio Code / Visual Studio for Mac

Examine the Up method.


<a name="test"></a>

Test the app

  • Run the app and append /Movies to the URL in the browser (http://localhost:port/movies).

If you get the error:

console
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 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.

  • Test the Edit, Details, and Delete links.

The next tutorial explains the files created by scaffolding.

Next steps

[!div class="step-by-step"] Previous: Get Started Next: Scaffolded Razor Pages

:::moniker-end