ASP.NET Core 6.0 Minimal API with Entity framework core
ASP.NET Core 6.0 Minimal API is the new breed of ASP.NET which helps us write API’s in much lesser code, it's something I have already discussed in my earlier post over here.
Goal
The goal of this article is to ensure, we complete all the setup and necessary pre-requisite required to wire up Entity framework within our ASP.NET Core minimal API controllers and ensure the data acess from SQL server DB is in place.
So, in this article we will do the following
- Install EF Core within our project
- Create DBContext access class
- Set Dependency Injection with service container
- Perform Entity Framework Database update/migrate to SQL server
Install EF Core within our project
To install EF Core within our existing project, lets add the following Nuget packages
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.8">
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.8" />
Create DBContext access class
DBContext will set the EF context for data access and set the DataSet for our model to access data from data source. We are going to call it as EmployeeDbContext
Here we will create the following
//Constructor with DbContextOptions and the context class itself
public EmployeeDbContext(DbContextOptions<EmployeeDbContext> options) : base(options)
{ }//Create the DataSet for the Employee public DbSet<Employee> Employee { get; set; }
Once created, we need to override the OnConfiguring method to read the connection string of database from SQL server via appsettings.json file
Set Dependency Injection with service container
This is done in our Program.cs file
var connectionString = builder.Configuration.GetConnectionString("AppDb");builder.Services.AddDbContext<EmployeeDbContext>(x => x.UseSqlServer(connectionString));
Finally, Entity Framework Database update via dotnet-ef
Pre-requisite:
Make sure you have already installed the dotnet-ef tool, which can be done something like this
Lets run the command from Powershell/Commandline as to start adding the database and create our first initial tables
To Add Database
dotnet ef database update
To add the migration
dotnet ef migrations add initialDb
The above will create the migration script for us
Complete video demonstration
Here is the complete video of the above article demonstration in action