ADO.Net Entity Data Model/Designersupports in.Net Frameworkbut not in.Net/EF Core.
To port an EF6 Model EDMX-Based Model to EF Core, regenerate a new code-based model using Scaffold-DbContext.
In this approach, (EF Core) we model our entities and database context as code-based similar to Code-First. 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 = Truefor Windows Authentication.User Id={Username}; Password={Password}for Standard Security.
"ConnectionStrings": { "DefaultConnection": "Server={ServerName};Database={DatabaseName};Integrated Security=True" } - Run
DotNet.EFCore.ModelFirst.RazorAppproject. CheckCRUD (Create-Read-Update-Delete)operations against database usingEntity Framework Core.
-
Skeleton
Code Structureas per requirements. -
Add dependent
NuGet Packages.Microsoft.EntityFrameworkCore.ToolsMicrosoft.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 = Truefor Windows Authentication.User Id={Username}; Password={Password}for Standard Security.
"ConnectionStrings": { "DefaultConnection": "{SQL Connection String}" } -
Create
ModelsandDatabase Context. UpdateOnConfiguringmethod in DbContext for getting connection string from JSON config file or some secure vault like Azure Key Vault etc. -
Launch
Package Manager Console. Choose project with EF NuGet Packages Installed (E.g.,DotNet.EFCore.ModelFirst.RazorApp) asDefaultandStartupProject.Visual Studio IDE --> Tools --> NuGet Package Manager --> Package Manager Console -
Create
DatabaseandTablesusingEntity Framework CoreorEntity 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-Databaseetc.)
- Migration commands to migrate database to latest version. (E.g.,
-
Create
DB Initializerwith 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 fromDbMigrationConfigurationin theMigrationsfolder.Enable-Migrations –EnableAutomaticMigration:$trueSet 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
[OPTIONAL] Enable-Migrations Add-Migration {MigrationName} Update-Database -VerboseEntity Framework Core Commands
[OPTIONAL] EntityFrameworkCore\Enable-Migrations EntityFrameworkCore\Add-Migration {MigrationName} EntityFrameworkCore\Update-Database -Verbose -
Register DbContext and DB Initializer in Application Builder Services Collection before performing Application Build either in
Program.csorStartup.cs.builder.Services.AddDbContext<{DB Context Name}>(); MyDbInitializer.Initialize(new {DB Context Name}()); -
Now
DbContextcan 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
PagesusingModels. -
Run
DotNet.EFCore.ModelFirst.RazorAppproject. CheckCRUD (Create-Read-Update-Delete)operations against database usingEntity Framework Core.
EntityFrameworkCore
.Net Core Razor Pages
EF Core - Razor Pages
EFCore - Get Started
EF - Model First