Section 9: Entity Framework - Introduction

 Section 9: Entity Framework


Introduction:


In previous sections, we created APIs and implemented CRUD operations using those APIs. But the data we used is static data; these data should be stored in a database.

We will use Entity Framework for our Database Operations. 

Entity Framework is one of ORMs. When we use EF, we don't have to write any DB query statements. EF does it for us.

Apart from this, consider this scenario. You have developed an API using mySQL as a database. But, after a few days, you get a requirement to change the database to DB2. Using EF, we just need to change a few configurations and database will be moved to DB2. After a few more months, you may get a requirement to change to AWS Aurora. Just change the configuration and you are done!

In Entity Framework, each Model class is converted to a table. This model class is called Entity.

Approaches of Entity Framework:

There are two approached when we use EF.
  1. Code -First: In this approach we write the code first and EF will create Database for us
  2. Database-First: In this approach, we create database first and EF will create code for us.


Legacy softwares usually uses database-First. 


DbContext, DBSet and Migrations

DBContext is a class in EF that helps in communication between the database and model/entity. In other words, it is a class mainly used for communicating with the database.

DBSet is a class that helps represent an entity set for CRUD operations. Each model should have a DBSet and using this we perform CRUD operations on that DB table/Model.

Steps to use EF:

  1. Install EF NuGet Packages.
  2. Create an Application DBContext class. Derive this class from DBContext. Application DBContext class should have a constructor and should take DBContextOptions as Parameter. DBContextOptions tell the EF what Database(Aurora / mySQL / etc) we are using and its location.
  3. Create DBSet. DBSet is each table in the database. Hence, for each Model class we should have a DBSet in Application DBContext class.
  4. We are almost done. EF should create tables for us in the Database. But, this happens when we do a migration. Migration is a process where EF will perform database operations based on the code. 

Let us see the above steps in next sections.