This post is about building Minimal API endpoints from EF Core DbContext. When building APIs using EF Core and Minimal APIs, most of the time we will be writing the same code again and again. Recently I found a nuget package - InstantAPIs - this package helps to generate CRUD APIs with Swagger (Open API) definition from DbContext class with two lines of code.
To get started I am creating an empty web application using the command
dotnet new web -o MinimalWebApiExample. Once it is done, I am adding reference of following nuget packages.
Next I am creating a Model and DbContext class, like this.
And here is the DbContext class.
Once it is done, add connection strings in appsettings.json file, modify the
Program.cs to include DbContext class.
Next create and apply migrations using following commands.
Next we can generate Minimal API endpoints using
InstantAPIs. To do this, update the Program.cs file like this.
Now let us run the application using
dotnet run command. And browse the application and navigate to
/swagger endpoint, you will be able to see the API endpoints for Person object like this.
Check out the Instant APIs project from GitHub
I found one issue when I tried to build minimal APIs with scaffolded entities and db context with NorthWind database. Later I identified the issue - InstantApis package generate endpoints using Primary key in the table / entity - for some entities there was not primary key - it was attributed with
[Keyless] attribute. InstantApis was not considering this attribute and throwing an exception. So if you’re generating the API using scaffolded database entities, make sure all the entities got a primary key.
Happy Programming :)