In this article, I am going to discuss the Entity Framework Context Class in C# with Examples. Please read our previous article where we discussed the Architecture of Entity Framework in Detail. At the end of this article, you will understand what exactly the Context Class is and when and how to use this Context Class in Entity Framework with Examples.
The Entity Framework allows us to Query, Insert, Update, and Delete data using Common Language Runtime (CLR) objects which are also known as Entities (or .NET Classes). The Entity Framework maps the entities (classes) and relationships that are defined in our model to a database.
The primary class that is responsible for interacting with the database is System.Data.Entity.DbContext. The Context class in Entity Framework is a class that derives from DBContext in EF 6. It is an important class in Entity Framework, which represents a session with the underlying database. The DbContext class belongs to System.Data.Entity namespace.
According to MSDN, A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
We are going to work with the same example that we created in our Introduction to Entity Framework article. In that console application, we retrieve the data from the SQL Server database using Entity Framework.
First, let’s have a look at 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.
The following EF_Demo_DBEntities class is an example of a context class that is created by Entity Framework using C# Language.
In the above code, as you can see 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 i.e. using this context class we can perform the SELECT, INSERT, UPDATE, and DELETE database operations on the database tables.
Further, if you notice this context class has one parameterless constructor and this constructor is calling the DbContext class parameterized constructor by passing EF_Demo_DBEntities as the value for the Name parameter. Here, you need to pass either the database name or the connection string name. Here, we are passing the connection string name. If you remember while adding the ADO.NET Entity DataModel, we specified the connection string name as EF_Demo_DBEntities, and Entity Framework will create the connection string in the App.Config file. Now, if you go to the App.Config file, then you will see that the connection string created with the name EF_Demo_DBEntities is as follows:
<connectionStrings>
<add name=”EF_Demo_DBEntities” connectionString=”metadata=res://*/EmployeeDataModel.csdl|res://*/EmployeeDataModel.ssdl|res://*/EmployeeDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=LAPTOP-ICA2LCQL\SQLEXPRESS;initial catalog=EF_Demo_DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"” providerName=”System.Data.EntityClient” />
</connectionStrings>
So, when we are going to perform the CRUD operation using the above Entity Framework context class, it is going to use the above connection string and going to perform the database operation on the database.
Note: If we are using Entity Framework in Desktop Applications like Console, and Windows Form, then Entity Framework will add the connection string in App.Config file and if we are using Entity Framework in a Web Application like Web Form, MVC, and Web API then Entity Framework will add the connection string in Web.Config file.
In order to understand how to query using the Entity Framework Context class, please modify the Program class as shown below. The following example code is self-explained, so please go through the comment lines.
In the above example, I am showing how to query using the Entity Framework Context Class and in our upcoming articles, I will show you how to perform INSERT, UPDATE, and DELETE operations using Entity Framework Context Class. Now, if you want to check what SQL Command is generated by the Entity Framework, then you can take the help of the SQL Profiler tool using SSMS. The following SQL commands are generated by Entity Framework for the above example.
To Fetch all the Departments i.e. DBEntities.Departments.ToList(), the following script is generated by the Entity Framework
SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name],
[Extent1].[Location] AS [Location]
FROM [dbo].[Departments] AS [Extent1]
To Fetch all Employees of Each Department i.e dept.Employees, the following script is generated by the Entity Framework and the following SQL Statement will be executed for each department.
exec sp_executesql N’SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Name] AS [Name],
[Extent1].[Email] AS [Email],
[Extent1].[Gender] AS [Gender],
[Extent1].[Salary] AS [Salary],
[Extent1].[DepartmentId] AS [DepartmentId]
FROM [dbo].[Employees] AS [Extent1]
WHERE [Extent1].[DepartmentId] = @EntityKeyValue1′,N’@EntityKeyValue1 int’,@EntityKeyValue1=1
Now, if you go to the definition of the Department Entity (class) which is auto-generated by the Entity Framework, then you will see that along with the ID, Name, and Location properties, it also has one property Employees which is a collection type as shown in the below image.
The DbContext class is one of the important classes in Entity Framework. It is a bridge between your domain or entity classes and the underlying database. For a better understanding, please have a look at the below image.
So, the following are the major responsibilities performed by the DbContext class:
In the next article, I am going to discuss the Entities in the Entity Framework in Detail with Examples. Here, in this article, I try to explain the Context Class in Entity Framework with Examples. 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