DbContext Class in Entity Framework Core

DbContext Class in Entity Framework Core

DbContext Class in Entity Framework Core

DbContext class is the brain of Entity Framework Core, using it you can do all the communications with the database. It allows performing the following tasks:

  • 1. Managing database connection.
  • 2. Configuring entities and the relationships between them.
  • 3. Reading, creating, updating & deleting data in the database.
  • 4. Configuring change tracking.
  • 5. Caching
  • 6. Transaction management

Using DbContext class in your application

In order to use the features of DbContext class, your application context class has to derive from it.

Take for example – for the company’s database (see the previous tutorial), you can create a new context class and name it CompanyContext.cs. Place this class inside the Models folder

Now derive it from DbContext class that lies under the using Microsoft.EntityFrameworkCore; namespace.

The CompanyContext.cs will look like this:

public class CompanyContext : DbContext
{
    
}

Next add the DbSet for the 2 entity class. These are the Department and Employee.

This will make your CompanyContext class look this way:

public class CompanyContext : DbContext
{
    public DbSet<Department> Department { get; set; }
    public DbSet<Employee> Employee { get; set; }
}
The DbSet class represents a collection for a given entity within the model and is the gateway to database operations against an entity.

You may remember in the company database there are 2 tables – Department & Employee, so the 2 entity classes will be Department.cs and Employee.cs. Place these classes inside the Models folder.

The structure of these files are:

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Employee> Employee { get; set; }
}
public class Employee
{
    public int Id { get; set; }
    public int DepartmentId { get; set; }
    public string Name { get; set; }
    public string Designation { get; set; }

    public Department Department { get; set; }
}   

The OnConfiguring() method

The OnConfiguring() method of the DbContext class is overridden inside the context class (i.e. here CompanyContext.cs). It allows to select and configure the data source to be used with a context using DbContextOptionsBuilder which is passed to its parameter.

On adding the OnConfiguring() method to the CompanyContext class, it will look like:

public class CompanyContext : DbContext
{
    public DbSet<Department> Department { get; set; }
    public DbSet<Employee> Employee { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
         optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
        }
    }
}

I have passed the connection string to the UseSqlServer() of the DbContextOptionsBuilder().

The OnModelCreating() method

The OnModelCreating() method of the DbContext class allows configuring the model using ModelBuilder Fluent API. This method is overridden inside the context class (i.e. here CompanyContext.cs).

After adding it to the CompanyContext class it will look:

public class CompanyContext : DbContext
{
    public DbSet<Department> Department { get; set; }
    public DbSet<Employee> Employee { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
         optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Department>(entity =>
        {
            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(50)
                .IsUnicode(false);
        });

        modelBuilder.Entity<Employee>(entity =>
        {
            entity.Property(e => e.Designation)
                .IsRequired()
                .HasMaxLength(25)
                .IsUnicode(false);

            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(100)
                .IsUnicode(false);

            entity.HasOne(d => d.Department)
                .WithMany(p => p.Employee)
                .HasForeignKey(d => d.DepartmentId)
                .OnDelete(DeleteBehavior.ClientSetNull)
                .HasConstraintName("FK_Employee_Department");
        });
    }
}

Inside the OnModelCreating() method I have configured both the Department and the Employee entities.

As you can see, by using the IsRequired() I am making the Name property of the Department class as the required one.

Similarly the HasMaxLength(100) method is used to set the maximum length of Designation property of the employee.

DbContext Methods:

Method Description
Add Adds a new entity with Added state
AddRange Adds a collection of new entities with Added state
Attach Attaches a new or existing entity with Unchanged state
AttachRange Attaches a collection of new or existing entity with Unchanged state
Remove Attaches an entity with Deleted state
RemoveRange Attaches a collection of entities with Deleted state
Update Attaches disconnected entity with Modified state
UpdateRange Attaches collection of disconnected entity with Modified state
SaveChanges Execute INSERT, UPDATE or DELETE command to the database for the entities with Added, Modified or Deleted state.

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.