In this approach, we model our entities and database context along with Entity Type Configuration. Then either using Migrations or DB Initializer, we create the database.
Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views.
Language : C#
.Net Version : >=6.0
- Microsoft.AspNetCore.App>=6.0
- Microsoft.NETCore.App>=6.0
- Microsoft.EntityFrameworkCore.Tools>=6.0
- Microsoft.EntityFrameworkCore.SqlServer>=6.0
- Microsoft.VisualStudio.Web.CodeGeneration.Design>=6.0
- Visual Studio IDE
- Microsoft SQL Server
- Azure Data Studio / SQL Server Management Studio (SSMS) / SSDT for Visual Studio
- Have SQL Server ready with either existing or no database and get/make connection string.
- Update SQL Connection String in
appsettings.json
.Integrated Security = True
for Windows Authentication.User Id={Username}; Password={Password}
for Standard Security.
"ConnectionStrings": { "DefaultConnection": "Server={ServerName};Database={DatabaseName};Integrated Security=True" }
- Run
DotNet.EFCore.CodeFirstFluentApi.RazorApp
project. CheckCRUD (Create-Read-Update-Delete)
operations against database usingEntity Framework Core
.
-
Skeleton
Code Structure
as per requirements. -
Add dependent
NuGet Packages
.Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
-
Have SQL Server ready with either existing or no database and get/make connection string.
-
Update SQL Connection String in
appsettings.json
.Integrated Security = True
for Windows Authentication.User Id={Username}; Password={Password}
for Standard Security.
"ConnectionStrings": { "DefaultConnection": "{SQL Connection String}" }
-
Create
Models
,Entity Type Configuration
andDatabase Context
.- Update
OnConfiguring
method in DbContext for getting connection string from JSON config file or some secure vault like Azure Key Vault etc.optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure());
- Update
OnModelCreating
method in DbContext for adding/applying Entity Type Configuration onModelBuilder
.// Default Schema modelBuilder.HasDefaultSchema("dbo");
// Apply entity type configuration modelBuilder.ApplyConfiguration(new EmployeeConfiguration());
- Update
-
Launch
Package Manager Console
. Choose project with EF NuGet Packages Installed (E.g.,DotNet.EFCore.CodeFirstFluentApi.RazorApp
) asDefault
andStartup
Project.Visual Studio IDE --> Tools --> NuGet Package Manager --> Package Manager Console
-
Create
Database
andTables
usingEntity Framework Core
orEntity Framework
.Automated Migration
- DB Initializer - C# code to ensure database creation and its data.
- Enable Migration with Automatic MigrationsEnabled (Entity Framework).
Code Migration
- Migration commands to migrate database to latest version. (E.g.,
Add-Migration
,Update-Database
etc.)
- Migration commands to migrate database to latest version. (E.g.,
-
Create
DB Initializer
with a method injected withDB Context
. Then add required entities and data to the context and save changes.public static class MyDbInitializer { public static void Initialize(MyDbContext context) { // Ensuring Database context exists when Database exists or newly created. context.Database.EnsureCreated(); if (context.Employees.Any()) return; // Db has been seeded // Employees Sample Data var employees = new Employee[] { Name = "Arjun", Email = "arjun@abc.com", Phone = 9876543210, IsActive = true } }; // Adding Entities sample data to Context context.Employees.AddRange(employees); // Saving Changes to DB Context context.SaveChanges(); } }
-
[OPTIONAL]
Entity Framework Option - Enable Automatic Migrations using below command. Once executed, it will create an internal sealed Configuration class derived fromDbMigrationConfiguration
in theMigrations
folder.Enable-Migrations –EnableAutomaticMigration:$true
Set the database initializer in the context class to
MigrateDatabaseToLatestVersion. Database.SetInitializer(new MigrateDatabaseToLatestVersion<{DBContext Name}, EF6Console.Migrations.Configuration>());
-
Commands for Code Migration (either 8 or this step).
Entity Framework Commands
Enable-Migrations Add-Migration {MigrationName} Update-Database -Verbose
Entity Framework Core Commands
EntityFrameworkCore\Enable-Migrations EntityFrameworkCore\Add-Migration {MigrationName} EntityFrameworkCore\Update-Database -Verbose
-
Run
DotNet.EFCore.CodeFirstFluentApi.RazorApp
project. CheckCRUD (Create-Read-Update-Delete)
operations against database usingEntity Framework Core
. -
Register DbContext and DB Initializer in Application Builder Services Collection before performing Application Build either in
Program.cs
orStartup.cs
.builder.Services.AddDbContext<{DB Context Name}>(); MyDbInitializer.Initialize(new {DB Context Name}());
-
Now
DbContext
can be injected inPage .cs file (page.cshml.cs)
and can be used to access database. -
Create Razor Page under Pages with Folder Organization with either
Razor Page with Entity Framework Core (CRUD)
orRazor Page Empty
. -
[OPTIONAL] Implement either
Repository/Unit of Work(UoW)/Factory Pattern etc
., to separte operations based on entity using injectedDbContext
. -
Pass transactional data to
Pages
usingModels
.
EntityFrameworkCore
.Net Core Razor Pages
EF Core - Razor Pages
EFCore - Get Started
EF Core - Fluent API
EF Core - Modeling