Adding Entity Framework Core

microservices csharp efcore aspnetcore

This is the second post in the microservices architecture series.

The goal of this post is to add Entity Framewore core to the sample application and make a simple database call to verify that it works.

Sample Application

Download the sample app from here and walkthrough the changes in the next section.

Tooling

Source Code Changes

  • SampleApi1.csproj - The Entity Framework references have been added to the project.

  • Person.cs - The model class that is used to work with the database.

  • PersonContext - The DbContext` class.

  • PersonEntityTypeConfiguration.cs - The class where we configure the Person entity type.

  • PersonContextSeed.cs - This is where we create sample people for seeding the database.

  • CustomExtensions.cs - Contains one method called AddCustomDbContext at the moment which is called from Program.cs.

  • IHostExtensions.cs - Contains extension methods to IHost. Currently just one method MigrateDbContext is called from Program.cs.

  • Program.cs - This is where we add the AddDBContext to the ServicesCollection and call MigrateDbContext which seeds the database.

  • PersonController.cs - Contains the standard CRUD actions that connect to the database and performs corresponding crud operations.

Verification

  • F5 should start debugging the docker compose file.

  • You should be able to see the swagger file for SampleWebApi1 project using the /swagger link.

  • Test the PersonController.