DbContext Class in Entity Framework Core

In this tutorial you will learn how to create DbContext class in entity framework core to connect sql sever. DBContext is the core API that provides all functionality for object mapping, connecting database and performing all database related operations.

Here we create DbContext Class, read all database related information from appsettings.json file and connect SQL server database to perform all database related operations.

DbContext Class comes under Microsoft.EntityFrameworkCore namespace, the core dbContext class is inherited from many interfaces like IInfrastructure, IDbContextDependencies, IDbSetCache, IDbContextPoolable etc.

This assembly doesn’t come with default project (when you create project for the first time), so you need to install Microsoft.EntityFrameworkCore package from nuget package manager.

Entity Framework Core DbContext Example

Go to package manager and install Microsoft.EntityFrameworkCore

This is how the DbContext Class will look like.

Note: "DbContextOptionsBuilder" does not contain a definition for "UseSqlServer", this is actually an extension method, so you also need to install Microsoft.EntityFrameworkCore.SqlServer assembly from nuget package manager, if you are trying to connect mysql database then you may need to install additional assembly for mysql connection.

Here are few points you need to understand

  • You need a reference of using Microsoft.EntityFrameworkCore namespace and "DbContext" class
  • Using static connection string of Startup.cs class
  • Override onConfiguring , setting up extension method for respective data provider, (here UseSqlServer())
  • Creating DbSet property for mapping with database table, property name should be same as table name.
  • Creating DbSet property for mapping with database table, property name should be same as table name.
Custom Class Inherit from DbContext Base Class

This is how you can design customised DbContext class in your application, Look at the beloe "EFContext : DbContext" class, this is working code sample

using Microsoft.EntityFrameworkCore;
/// <summary>
/// Written by WebTrainingRoom.Com
/// </summary>
namespace AspNetCoreMVC
{
public class EFContext : DbContext
{
public EFContext() : base()
{
}
public static string GetConnectionString()
{
return Startup.DbConnectionString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
var _connectionString = GetConnectionString();
optionsBuilder.UseSqlServer(_connectionString);
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().HasKey(s=>s.StuId);
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<Student> tbStudent { get; set; }
    }
}

The above DBContext class code is well tested working code; you can start using in your application

Now you can write any database related operation using above EFContext class, here is an example of adding student to database using dbcontext class.

public Student AddStudent(Student s)
{
    using (EFContext context = new EFContext())
    {
        context.tbStudent.Add(s);
        context.SaveChanges();
    }
    return s;
}

You may be interested to read following tutorials

 
Entity Framework Core DbContext
Learn entity framework orm using c#, entity framework core and earlier version of entity framework, all tutorials are written in c#.
Entity Framework Interview Questions

SQL interview questions
Entity Framework C# Examples | Join .Net C# Course