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.
The Model-View-Controller (MVC)
architectural pattern separates an application into three main groups of components: Models, Views, and Controllers. This pattern helps to achieve separation of concerns. Using this pattern, user requests are routed to a Controller which is responsible for working with the Model to perform user actions and/or retrieve results of queries. The Controller chooses the View to display to the user, and provides it with any Model data it requires.
The ASP.NET Core MVC framework is a lightweight, open source, highly testable presentation framework optimized for use with ASP.NET Core.
ASP.NET Core MVC provides a patterns-based way to build dynamic websites that enables a clean separation of concerns. It gives you full control over markup, supports TDD-friendly development and uses the latest web standards.
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
- Newtonsoft.Json>=11.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.MvcApp
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.MvcApp
) 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.MvcApp
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 inController
and can be used to access database. -
Implement either
Repository/Unit of Work(UoW)/Factory Pattern etc
., to separte operations based on entity using injectedDbContext
. -
Pass transactional data to
Views
usingModels
.
EntityFrameworkCore
.Net Core MVC
EFCore - Get Started
EFCore - MVC
EF Core - Fluent API
EF Core - Modeling