Context Class in Entity Framework

Context Class in Entity Framework

The Entity Framework enables us to query, insert, update, and delete data using Common Language Runtime (CLR) objects which is also known as entities. The Entity Framework maps the entities and relationships that are defined in our model to a database. In this article, I will discuss the Context Class in Entity Framework in details.

The primary class that is responsible for interacting with data as objects is System.Data.Entity.DbContext. 

The context class in Entity Framework is a class which derives from DBContext in EF 6 and EF Core both. It is an important class in Entity Framework, which represents a session with the underlying database.

Please read Introduction to Entity Framework article of this article series. We are going to work with the same example that we created in the Introduction to Entity Framework article, so please read the Introduction to Entity Framework article before proceeding to this article.

In the Introduction to Entity Framework article, we created one console application which will retrieve the data from a SQL Server database using Entity Framework.

First, let’s have a look into the solution. Please double click on the EF_Demo_DBEntities which is inside the EmployeeDataModel.Context.cs which is inside EmployeeDataModel.Context.tt file as shown below.

Context Class in Entity Framework

The following EF_Demo_DBEntities class is an example of a context class which is created by Entity Framework.

namespace EFDemo
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class EF_Demo_DBEntities : DbContext
    {
        public EF_Demo_DBEntities()
            : base("name=EF_Demo_DBEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Department> Departments { get; set; }
        public virtual DbSet<Employee> Employees { get; set; }
    }
}

In the above example, the EF_Demo_DBEntities class is derived from DbContext class which makes it a context class. It also includes an entity set for Departments and Employees entities.

The context class is used to query or save data to the database. It is also used to configure domain classes, database related mappings, change tracking settings, caching, transaction etc. which we will discuss in details in our upcoming articles.

Let’s see how to query using context class.

Open the main method of Program class and copy and paste the following code.

namespace EFDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EF_Demo_DBEntities DBEntities = new EF_Demo_DBEntities())
            {
                List<Department> listDepartments = DBEntities.Departments.ToList();
                Console.WriteLine();
                foreach(Department dept in listDepartments)
                {
                    Console.WriteLine("  Department = {0}, Location = {1}", dept.Name, dept.Location);
                    foreach(Employee emp in dept.Employees)
                    {
                        Console.WriteLine("\t Name = {0}, Email = {1}, Gender = {2}, salary = {3}",
                            emp.Name, emp.Email, emp.Gender, emp.Salary);
                    }

                    Console.WriteLine();
                }
                Console.ReadKey();
            }
        }
    }
}

Run the application and see the results. We will discuss more Context class in a later article.

In the next article, I will discuss the Entities in Entity Framework.

SUMMARY

In this article, I try to explain Context class in Entity Framework with one example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article

Leave a Reply

Your email address will not be published. Required fields are marked *