Tool for HR, Hiring Managers, and the Leadership Team

What is DbContext and why do we use it?

What is DbContext in .NET?

DbContext is the main class in Entity Framework Core that is used to interact with the database.

It acts as a bridge between your application and the database.

In simple words:

DbContext = Database Connection + Change Tracking + Querying + Save Changes

Why Do We Use DbContext?

We use DbContext to:

✅ Query data from database
✅ Insert data
✅ Update data
✅ Delete data
✅ Track changes
✅ Manage database connection

Example Without Entity Framework

Without DbContext (ADO.NET style):

SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM Users", conn);

You manually handle:

  • Connection

  • Commands

  • Mapping

Example Using DbContext (EF Core)

Much cleaner:

var users = _context.Users.ToList();

DbContext handles everything internally.

Example DbContext Class

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Product> Products { get; set; }
}

What is DbSet?

public DbSet<User> Users { get; set; }

DbSet represents a table in the database.

DbSet Database Table
Users Users table
Products Products table

Example Usage in Service / Controller

public class UserService
{
    private readonly AppDbContext _context;

    public UserService(AppDbContext context)
    {
        _context = context;
    }

    public List<User> GetUsers()
    {
        return _context.Users.ToList();
    }
}

Insert Example

var user = new User
{
    Name = "John"
};

_context.Users.Add(user);
_context.SaveChanges();

Update Example

var user = _context.Users.First();
user.Name = "Updated";

_context.SaveChanges();

Delete Example

var user = _context.Users.First();
_context.Users.Remove(user);

_context.SaveChanges();

Important Responsibilities of DbContext

1. Database Connection

DbContext manages database connection automatically.

2. Change Tracking

user.Name = "New Name";
_context.SaveChanges();

EF automatically detects changes.

3. Querying Data

_context.Users.Where(x => x.Name == "John");

4. Save Changes

_context.SaveChanges();

Interview Definition (Best Answer)

If interviewer asks:

What is DbContext?

You can say:

"DbContext is the main class in Entity Framework Core used to interact with the database.
It manages database connections, tracks changes, and allows querying and saving data."

DbContext Lifecycle (Important Interview Question)

DbContext is usually registered as Scoped:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

Why Scoped?

  • One DbContext per request

  • Better performance

  • Avoid concurrency issues

Summary

Feature DbContext
Connect to DB Yes
Query data Yes
Insert/Update/Delete Yes
Change tracking Yes
Save changes Yes