Section 10: Entity Framework - Setting up DBContext


Section 10: Entity Framework - Setting up DBContext


 Introduction:

In the previous section, we have seen what is Entity Framework. Let us start implementing it in this section..

NuGet Packages


To use Entity Framework, we have to install a few NuGet Packages. The lists are as below:

  • Microsoft.EntityFrameworkCore.Tools
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer

The steps to install NuGet packages is as below:



Creation of DBContext class:

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.


To create a DBContext class,

  • Create a folder called, Data. Create a class called, AppDBContext.
  • Inherit AppDBContext  from DBContext.
  • Create a constructor for AppDBContext. In this constructor pass DBContextOptions to let EF know details about our database such as DB name, DB type.
  • Create a DBSet for Movie model.
Let us see this in action: