The tutorial below is based on "Get started with Razor Pages in ASP.NET Core" from docs.microsoft.com.
- Visual Studio 2019
- In the Visual Studio Installer, install the following workloads:
- ASP.NET and web development
- .NET Core cross-platform development
- Tutorial 1- Create a Razor Page application
In this section, we are adding classes to manage movies in a 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
.
using System;
namespace RazorPagesMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
}
- In Solution Explorer, right click on the Pages folder > Add > New Folder.
- Name the folder Movies
- In Solution Explorer, right click on the Pages/Movies folder > Add > New Scaffolded Item.
- In the Add Scaffold dialog, select Razor Pages using Entity Framework (CRUD) > Add.
- In the Model class drop down, select Movie (RazorPagesMovie.Models).
- In the Data context class row, select the + (plus) sign and set the name as RazorPagesMovie.Models.MovieContext.
- In the Data context class drop down, select RazorPagesMovie.Models.MovieContext.
- Select Add.
The generated code from the scaffold process creates the following files:
- Pages/Movies/
- Create
- Delete
- Details
- Edit
- Index
- Data/MovieContext.cs: Class that includes a
DbSet
property for the entity set. An entity set typically corresponds to a database table, and entity corresponds to a row in the table.
The scaffold process also modifies existing files:
- Startup.cs: Created a DB context and registered it with the dependency injection container
- appsettings.json: The connection string used to connect to a local database is added.
- From the Tools menu, select NuGet Package Manager > Package Manager Console.
- In the Package Manager Console enter the following commands:
Add-Migration Initial
Update-Database
- Press F5 to run the app
- Append /movies to the URL in the browser: http://localhost:port/movies
- Create a new entry with the Create link
- It works!
- Test the Edit, Details and Delete links
If you get a SQL exception, verify you have run migrations and updated the database.
Extra light read 7 minutes: If you want to read more on pages we just created click here for more information.
NEXT TUTORIAL - Modifying generated pages