chapter five

5 The refactor: setup and the database access layer

 

This chapter covers

  • Refactoring a legacy code base to be clean and secure
  • Using Entity Framework Core to query a database
  • Implementing the Repository/Service Pattern
  • Creating a new .NET Core solution and project using the command line.

The time has finally come. You are probably itching to fix some of the issues we saw in chapters 3 and 4, and now we get to do that. First things first, let’s make a game plan on how to tackle this refactor. It takes more than one chapter to do it well, but with a good game plan, we can get through it with little trouble. We know a couple of things we need to do differently:

  • o In chapter 2 we were told to to use .NET Core instead of .NET Framework for the new version of the Flying Dutchman Airlines service.
  • o We need to rewrite the endpoints to be clean code (in particular, adherence to the DRY principle). This allows the airline to be more resilient against future scalability and extensibility problems.
  • o There is a security vulnerability in how we treat the security string; we need to fix that. The security vulnerability is a hard-coded connection string.
  • o The objects and database do not match. We also need to fix that to ensure a perfect isomorphic relationship between the codebase and the database.
  • o We need to adhere to the OpenAPI file discussed in chapter 2 and shown in Appendix C.

5.1       Creating a .NET Core solution and project

5.2       Setting up and configuring a web service

5.2.1   Configuring a .NET Core web service

5.2.2   Using The Builder pattern in C#

5.2.3   Creating and using WebHostBuilder

5.2.4   Implementing te Startup class

5.2.5   Using the Repository Pattern for our web service architecture

5.3       Implementing the database access layer

5.3.1    Entity Framework Core and “Reverse-Engineering”

5.3.2   DbSet and the Entity Framework Core workflow

5.3.3   Configuration Methods and environment variables

5.3.4   Setting an environment variable on Windows

5.3.5   Setting an environment variable on OSX

5.3.6   Retrieving environment variables at runtime in your code

5.4       Exercises

5.5       Summary