In this article I will explain a simple tutorial with an example, how to use simple Entity Framework in ASP.Net Core (.Net Core 8) Razor Pages.
This article will explain how to configure Entity Framework and connect to SQL Server database and finally the fetched data is displayed in View in ASP.Net Core (.Net Core 8) Razor Pages.
Note: For beginners in ASP.Net Core (.Net Core 8) Razor Pages, please refer my article ASP.Net Core 8 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

Installing Microsoft.EntityFrameworkCore.SqlServer package using Nuget

In order to install Microsoft.EntityFrameworkCore.SqlServer library using Nuget, please refer my article Install Microsoft.EntityFrameworkCore.SqlServer 8 Nuget Package.
 
 

Database

Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 

Model

1. Once the package is successfully installed, create a Folder named Models in your project and then a new class by right clicking the Models folder and then click on Add and then New Item option of the Context Menu.
.Net Core 8: Entity Framework Tutorial in ASP.Net Core Razor Pages
 
2. Create the following properties inside the Model class as shown below.
Note: In this article, only four Columns will be displayed and hence four properties are added to the class.
 
public class Customer
{
    public string CustomerID { getset; }
    public string ContactName { getset; }
    public string City { getset; }
    public string Country { getset; }
}
 
 

Database Context

1. Now you will need to add a new class to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
.Net Core 8: Entity Framework Tutorial in ASP.Net Core Razor Pages
 
2. Inside the class, first inherit the EntityFrameworkCore namespace and then inherit the DbContext class.
Then using Dependency Injection, a Constructor is created DbContextOptions are passed as parameter and also the Constructor of base class i.e. DbContext class is inherited.
Note: For more details on Dependency Injection, please refer my article .Net Core 8: Dependency Injection in ASP.Net Core.
 
Finally, a DbSet Collection property of Customer Model class is created, which will be later used for holding the Data fetched from SQL Server database.
using EF_Core_Razor_8.Models;
using Microsoft.EntityFrameworkCore;
namespace EF_Core_Razor_8
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
 
        public DbSet<Customer> Customers { getset; }
    }
}
 
 

Adding the Connection String inside AppSettings.json

The following Connection String setting has been added in the AppSettings.json file.
{
 "ConnectionStrings": {
    "MyConn""Data Source=.\\SQL2022;Initial Catalog=Northwind;Integrated Security=True"
 }
}
 
 

Configuring Database Context in Program.cs

Inside the Program.cs file, the Connection String is read from the AppSettings.json file and is used to add the DbContext service to the WebApplicationBuilder class.
Note: For more details on reading Connection String inside the Program.cs file, please refer my article .Net Core 8: Read Connection String inside Program.cs from AppSettings.json file.
 
using EF_Core_Razor_8;
using Microsoft.EntityFrameworkCore;
 
var builder = WebApplication.CreateBuilder(args);
 
// Enabling MVC
builder.Services.AddMvc();
builder.Services.AddControllersWithViews();
string constr = builder.Configuration.GetSection("ConnectionStrings")["MyConn"];
builder.Services.AddDbContext<DBCtx>(options => options.UseSqlServer(constr));
 
var app = builder.Build();
 
//Configure Routes
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
});
 
app.Run();
 
 

Razor PageModel (Code-Behind)

The PageModel consists of following Handler method.

Handler method for handling GET operation

Inside this Handler method, the Top 10 records are fetched from the Customers Table of the Northwind database using Entity Framework and stored into Generic List collection of Customer class property.
public class IndexModel : PageModel
{
    private DBCtx Context { get; }
    public IndexModel(DBCtx _context)
    {
        this.Context = _context;
    }
 
    public List<Customer> Customers { get; set; }
 
    public void OnGet()
    {
        this.Customers = (from customer in this.Context.Customers.Take(10)
                          select customer).ToList();
    }
}
 
 

Razor Page (HTML)

HTML Markup

The HTML of Razor Page consists of an HTML Table for displaying the records.
Then, a FOR EACH loop will be executed over the Model property which will generate the HTML Table rows with the Customer records.
@page
@using EF_Core_Razor_8.Models
@model EF_Core_Razor_8.Pages.IndexModel
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h4>Customers</h4>
    <hr />
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>Customer Id</th>
            <th>ContactName</th>
            <th>City</th>
            <th>Country</th>
        </tr>
        @foreach (Customer customer in Model.Customers)
        {
            <tr>
                <td>@customer.CustomerID</td>
                <td>@customer.ContactName</td>
                <td>@customer.City</td>
                <td>@customer.Country</td>
            </tr>
        }
    </table>
</body>
</html>
 
 

Screenshot

.Net Core 8: Entity Framework Tutorial in ASP.Net Core Razor Pages
 
 

Downloads



Other available versions