In this article I will explain a simple tutorial with an example, how to use Entity Framework Code First Approach with existing Database in ASP.Net Core Razor Pages.
This article will explain how to configure Entity Framework Code first from database in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net Core Razor Pages and Entity Framework, please refer my article ASP.Net Core Razor Pages: Simple Entity Framework Tutorial with example.
 
 
Database
1. First you need to download the SQL file using the following link.
2. Once downloaded, you need to execute the SQL file in SQL Server Management Studio.
3. After execution you will see the following Database.
ASP.Net Core Razor Pages: EntityFramework Code First Approach with Existing Database
 
The Database also contains the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
ASP.Net Core Razor Pages: EntityFramework Code First Approach with Existing Database
 
The Table consists of following records.
ASP.Net Core Razor Pages: EntityFramework Code First Approach with Existing Database
 
 
Creating new ASP.Net Core Razor Pages Project
For more details on creating ASP.Net Core Razor Pages project, please refer my article ASP.Net Core Razor Pages: Hello World Tutorial with Sample Program example.
 
 
Configuring and connecting Entity Framework Code First from database
Now I will explain the steps to configure and connect Entity Framework Code first from database.
In order to generate the Entity Framework Code first model from existing database Table in ASP.Net Core Razor Pages, the Scaffold-DbContext command is used.
Note: In order for Scaffold-DbContext to generate an entity type, the database table must have a primary key.
 
Scaffold-DbContext has the following parameters:
1. Connection – It specifies the Connection String to the Database.
2. Provider – It specifies the Provider name to be used. In this case it is Microsoft.EntityFrameworkCore.SqlServer.
3. OutputDir – It specifies to set the Folder (Directory) where the classes will be generated. In this case it is set with Models Folder.
4. DataAnnotations – It specifies to use DataAnnotation attributes to configure the model.
Note: For more details about Scaffold-DbContext, please refer the link Scaffold-DbContext.
 
Now let’s run the Scaffold-DbContext command from Nuget Package Manager Console window using the following command.
Scaffold-DbContext "Data Source=.\SQL2019;Initial Catalog=CodeFirst;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -DataAnnotations
ASP.Net Core Razor Pages: EntityFramework Code First Approach with Existing Database
 
After successfully executed the command, the Models folder will look as shown below.
ASP.Net Core Razor Pages: EntityFramework Code First Approach with Existing Database
 
Finally, the Entity Model is ready with the following classes.
Generated Table class
public partial class Customers
{
    [Key]
    public int CustomerId { get; set; }
 
    [Required]
    [StringLength(100)]
    public string Name { get; set; }
 
    [Required]
    [StringLength(50)]
    public string Country { get; set; }
}
 
Generated Database Context
public partial class CodeFirstContext : DbContext
{
    public CodeFirstContext()
    {
    }
 
    public CodeFirstContext(DbContextOptions<CodeFirstContext> options)
        : base(options)
    {
    }
 
    public virtual DbSet<Customers> Customers { get; set; }
 
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
            optionsBuilder.UseSqlServer("Data Source=.\\SQL2019;Initial Catalog=CodeFirst;Trusted_Connection=True;");
        }
    }
 
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customers>(entity =>
        {
            entity.Property(e => e.Country).IsUnicode(false);
 
            entity.Property(e => e.Name).IsUnicode(false);
        });
    }
}
 
 
Razor PageModel (Code-Behind)
The PageModel consists of following Handler method.
Handler method for handling GET operation
Inside this Handler method, the Customer records are fetched from database using Entity Framework Code First Approach and assigned to the public property Customers.
Finally, the public property Customers is returned to the Razor Page.
public class IndexModel : PageModel
{
    public List<Customers> Customers { get; set; }
 
    public void OnGet()
    {
        using (CodeFirstContext context = new CodeFirstContext())
        {
            this.Customers = (from customer in context.Customers
                              select customer).ToList();
        }
    }
}
 
 
View
The HTML of Razor Page consists of an HTML Table.
A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@page
@model EF_CodeFirst_Razor_Core.Pages.IndexModel
@using EF_CodeFirst_Razor_Core.Models
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>CustomerId</th>
            <th>Name</th>
            <th>Country</th>
        </tr>
        @foreach (Customers customer in Model.Customers)
        {
            <tr>
                <td>@customer.CustomerId</td>
                <td>@customer.Name</td>
                <td>@customer.Country</td>
            </tr>
        }
    </table>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: EntityFramework Code First Approach with Existing Database
 
 
Downloads