Database first approach, Entity Framework Core in .NET 5
Before getting started, I assume you have some knowledge of Entity Framework and .NET Core.
Suppose you have a database and you want to use EF Core.
(If you don’t have, run the Database script and create a sample database.)
Let’s start
Step1: Create a .NET 5 project using Visual Studio. Of course you can use VS Code.
Step2: Install the required packages for Entity Framework, Entity Framework Tooling. Install the below packages using package manger console (PMC):
install-package Microsoft.EntityFrameworkCore.SqlServer
install-package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Tools
Step 3: In order to generate DbContext file and Entity (which represents the table in our database), we need to run the below command
Scaffold-DbContext “Server=.\SQLExpress;Database=EmployeDB;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
In above command server_details (holds the db connection string), db provider and the output folder where we want to generate our entities and DbContext file.
Step4: Let’s move the connection string to AppSettings.json file and read it from their.
“ConnectionStrings”: {
“DefaultConnection”: “Server=.\SQLExpress;Database=EmployeDB;Trusted_Connection=True;”
}
EF Core does not provide a parameter-less constructor, instead you must pass a parameter of type DbContextOptions. This parameter is usually used to configure some context options such as what type of database connection string is used.
Update the constructor of EFCoreDBFirstContext with DbContext.
Note: I have moved the EFCoreDBFirstContext class from Models folder to Context folder
Now add the DbContext service into execution pipeline
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<EFCoreDBFirstContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));services.AddControllersWithViews();
}
Step5: Add a controller Employee (MVC Controller with views, using Entity Framework) and select the values accordingly.
Now you can run the application
Feel free to drop a question or feedback in comment section, will be more than happy to respond :)