0
0
CsharpConceptBeginner · 4 min read

What is DbContext in C#: Explanation and Example

DbContext in C# is a class that manages database connections and operations using Entity Framework Core. It acts like a bridge between your code and the database, allowing you to query and save data easily.
⚙️

How It Works

Think of DbContext as a manager that handles all communication between your application and the database. It keeps track of the data you want to work with, like a personal assistant organizing your tasks.

When you want to get data or save changes, DbContext translates your requests into database commands behind the scenes. It also remembers which data has changed so it can update the database correctly.

💻

Example

This example shows a simple DbContext class for managing a list of books and how to add and retrieve data.

csharp
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

// Define a Book entity
public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

// Define the DbContext
public class LibraryContext : DbContext
{
    public DbSet<Book> Books { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseInMemoryDatabase("LibraryDB");
    }
}

class Program
{
    static void Main()
    {
        using var context = new LibraryContext();

        // Add a new book
        context.Books.Add(new Book { Title = "1984", Author = "George Orwell" });
        context.SaveChanges();

        // Retrieve and print all books
        foreach (var book in context.Books)
        {
            Console.WriteLine($"{book.Id}: {book.Title} by {book.Author}");
        }
    }
}
Output
1: 1984 by George Orwell
🎯

When to Use

Use DbContext when you want to work with databases in C# using Entity Framework Core. It simplifies tasks like reading, adding, updating, and deleting data without writing raw SQL queries.

It's perfect for applications that need to store data persistently, such as web apps, desktop apps, or services that manage user information, products, or any data records.

Key Points

  • DbContext manages database connections and tracks data changes.
  • It provides DbSet properties to represent tables in the database.
  • It translates your C# code into database commands automatically.
  • Use it with Entity Framework Core for easier data access.

Key Takeaways

DbContext is the main class to interact with databases in Entity Framework Core.
It tracks changes and manages data operations like add, update, and delete.
You define DbSet properties in DbContext to represent your database tables.
Use DbContext to avoid writing raw SQL and simplify database work.
It works well for apps that need to store and retrieve data persistently.