Context Class in Entity Framework

The context class is a very important class while working with EF 6 or EF Core. It represents a session with the underlying database using which you can perform CRUD (Create, Read, Update, Delete) operations.

The context class in Entity Framework is a class which derives from System.Data.Entity.DbContext in EF 6 and EF Core both. An instance of the context class represents Unit Of Work and Repository patterns wherein it can combine multiple changes under a single database transaction.

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.

The following SchoolContext class is an example of a context class.

using System.Data.Entity;
public class SchoolContext : DbContext
{
 public SchoolContext()
 {
 }
 // Entities  
 public DbSet<Student> Students { get; set; }
 public DbSet<StudentAddress> StudentAddresses { get; set; }
 public DbSet<Grade> Grades { get; set; }
} 

In the above example, the SchoolContext class is derived from DbContext, which makes it a context class. It also includes an entity set for Student, StudentAddress, and Grade entities (learn about it next).

Learn more about the context class in the EF 6 DbContext and EF Core DbContext chapters.

AltStyle によって変換されたページ (->オリジナル) /