Databases and Razor
The set up for working with a database with Razor Pages is similar to that of MVC.
Entity Framework Package Requirements
Entity Framework can be used to set up the backend database. Objects are again used to save and retrieve data from the database.
To use Entity Framework requires adding additional packages to Visual Studio. The following packages are required:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.tools
In Visual Studio packages are managed through:
Note: The tutorial will make use of the local SQL Server ((localdb)\MSSQLLocalDB) provided as part of Visual Studio.
Create a Model
As with MVC to use Entity Framework we need to set up a Model. This model will map to a database table.
You can use exactly the same 'Films' table created for the MVC examples.
Storing the Connection String in appsettings.json
As with MVC appsettings.json is used to store a 'Connection String'.
The above shows the connection string for a Local MSSQL database of name 'MyFilmsDb'. This will be stored on a local server (localdb)\\mssqllocaldb.
Creating a Context
Again as with MVC we need to set up a DbContext. We'll save it as Models/ApplicationDbContext.cs
Configuring the Startup.cs
Following the same technique as MVC the DbContext is configured in Startup.cs to facilitate Dependency Injection.
In the ConfigureServices() method the AddDbContext is used to register the DbContext as a service.
Under services.AddRazorPages(); add:
Ensure the correct packages are available with:
Migrate and Build
If you don't have the database from the MVC examples, the same Entity Framework console commands could be used to run the migration command and then update the database.
Add-Migration Initial
Update-Database
It is important to run both console commands. The Add-Migration command can be given a name by the developer. It this example, it was sensible to call it Initial.