Razor Pages Database First using EF Core 8
If you have not completed the Console application, please consider altering the database as shown at the top of that tutorial.
This tutorial uses Visual Studio Code and therefore requires lots of command-line work. But that means you can follow this tutorial on any computer operating system worth it's salt.
Setting up the project
First we are going to create a folder for our project. I named mine RazorDemo2025. Created? Great! Now open that folder in VS Code.
- Make sure you have the C# Dev Kit extension installed (it will install several other things too).
- Ctrl+Shift+P (Windows) | Cmd+Shift+P (Mac), Type Project (you will see ".NET: new Project..." come up).
- In the template options type Razor and select "ASP.NET Core Web App (Razor Pages) MVC, Razor Pages, Web
Name: RazorDemo (you can now select the defaults for the remaining options) Enter ....
Setup the tooling...
First let's check to see what the latest version is:
dotnet ef --version
If you didn't get something satisfactory for your project, you can install it.
#To search for versions of a tool/package. dotnet package search dotnet-ef --exact-match #To install a particular version dotnet tool install --global dotnet-ef --version 8.0.13 #To update to a particular version dotnet tool update --global dotnet-ef --version 8.0.13
We also need the dotnet-aspnet-codegenerator (looks like today the latest version is 8.0.7:
dotnet tool install --global dotnet-aspnet-codegenerator --version 8.0.7
Setup the packages
Before we install any of these packages, we need to be in the project folder where we can see the .csproj file.
cd RazorDemo
dotnet add package Microsoft.EntityFrameworkCore --version 8.0.13 dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 8.0.13 dotnet add package Microsoft.EntityFrameworkCore.Tools --version 8.0.13 dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.0.13 dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --version 8.0.7
Scaffolding Up the DbContext
First, create a Models directory in the RazorDemo folder. Assuming I'm using a Docker instance of SQL Server 2022, I can create the DbContext and the Model files all with one command.
Next we are going to create a Default Connection String in the appsettings.json folder:
"ConnectionStrings": { "DefaultConnection": "Server=.;Database=UniversitySmall;UID=sa;Password=Password234;TrustServerCertificate=True;MultipleActiveResultSets=true" },
Now that we have added that to the appsettings.json file, we can use it when we are scaffolding.
dotnet ef dbcontext scaffold "Name=ConnectionStrings:DefaultConnection" Microsoft.EntityFrameworkCore.SqlServer -c UniversityContext -o Models -f
Check out the contents of your Models folder
We do need to make one thing clearer. When we scaffold up the UniversityConnection it creates a method in the UniversityContext class that looks like following:
1 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
2 => optionsBuilder.UseSqlServer("Name=ConnectionStrings:DefaultConnection");
It is possible to designate the connection string when we register the UniversityContext with the IOC container next. If we were to do that, we can have the OnConfiguring(...) do nothing. Just remove the body as follows:
1 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { }
Because, we can scaffolded the connection correctly with the full path to the connection string, it will work in the program as is allowing us to leave off the options => options.UseSqlServer(...) part of the registration of the DbContext in the next section.
Registering the DbContext with your IOC container
In program.cs add the following code before the var app = builder.Build();
1 builder.Services.AddDbContext<UniversityContext>()
If you get an error relating to not finding a connection string or a named connection, you can take option 2 above and add the connection string here like this:
1 //OPTIONAL IF THE FIRST ONE CAUSED ERRORS
2 builder.Services.AddDbContext<UnivesityContext>(options =>
3 options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
Hence, when using this in an IOC container, we can define provide the connection string in one of these two places and it will work.
Don't forget to add the appropriate using statements at the top:
1 using Microsoft.EntityFrameworkCore;
2 using RazorDemo.Models;
Go ahead and build your project to make sure that it builds at this point. If there are any errors or warnings you should take care of them before continuing.
Scaffolding a Student Page
Now let's scaffold pages to perform CRUD operations on the student table. While we are still in the project folder:
dotnet-aspnet-codegenerator razorpage -m Student -dc UniversityContext -udl -outDir Pages\Students -scripts
What does all that mean? Take a look at the documentation here
Now inspect the Pages/Students folder. Interesting right? We'll let's build it and see what it does.