Asp.Net Core Dbcontext And Dbset Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET Core DbContext and DbSet

Explaining ASP.NET Core DbContext and DbSet in Detail with Important Information

DbContext

  • Definition: DbContext is a bridge between the domain or entity objects in memory and the database in your application. It's essentially a session with the database and can be used to query and save instances of your entities.

  • Lifecycle: Typically, a single instance of DbContext is tied to a single web request in an ASP.NET Core application.

  • Responsibilities:

    • Connection Management: Maintains a database connection for querying and saving data.
    • Change Tracking: Keeps track of changes to entities that have been loaded into memory and are linked to the context.
    • State Management: Manages the state of entities (Added, Modified, Deleted, Unchanged, Detached).
    • Query Generation: Translates LINQ queries into SQL commands for execution.
    • Transaction Management: Controls when changes are saved to the database.
  • Configuration:

    • DbContext can be configured in Startup.cs or Program.cs (in modern ASP.NET Core applications starting from 3.0).
    • Developers often use Dependency Injection (DI) to configure DbContext.
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

DbSet

  • Definition: DbSet is a property on DbContext which represents a table in the database or a view for queries. It is a generic type that takes an entity type parameter.
  • Usage:
    • DbSet provides methods like Add, Find, Remove, and Attach for managing entities.
    • You can perform queries and manipulate the data in these sets, and then save changes back to the database using the SaveChanges method of DbContext.
public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Blog> Blogs { get; set; }
    // other DbSets for other entities
}

Important Information

  1. Change Tracking: Understanding how EF Core tracks changes to database entities is crucial. EF Core automatically tracks changes to entities loaded from the database, and these changes are then saved to the database when SaveChanges is called. This is handled through the EntityState (Added, Modified, Deleted, Detached, Unchanged).

  2. Lazy Loading: Lazy loading is a feature that automatically loads related data from the database the first time a navigation property is accessed. It can be enabled through proxies or through the explicit loading API. However, care should be taken when enabling lazy loading; it may lead to performance issues if not managed properly due to the number of round trips to the database.

  3. Eager Loading: Unlike lazy loading, eager loading is a way to load related data along with the primary data. This is done using the Include method. Eager loading can significantly reduce the number of queries sent to the database, which can improve performance.

  4. Explicit Loading: Explicit loading allows you to load related entities on demand by explicitly invoking a method. This can be useful when you only need certain related entities under specific conditions.

  5. Asynchronous Operations: EF Core supports asynchronous operations, making it easier to perform data access operations without blocking the main thread. Methods like ToListAsync, FirstOrDefaultAsync, and SaveChangesAsync are provided for asynchronous operations.

  6. Transactions: EF Core supports transaction management. You can control when changes are saved to the database using transactions by leveraging DbContext.Database.BeginTransaction() or by wrapping your work with DbContext.Database.ExecuteSqlRaw within a transaction scope.

  7. Database Migrations: EF Core has a robust migration system that allows you to evolve your database schema over time. This system is built on the DbContext and DbSet model, making it easier to manage changes to the database schema using code-first development.

  8. Performance Optimization: EF Core provides several mechanisms to optimize performance, including bulk operations, query compilation caching, and eager loading versus lazy loading strategies.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET Core DbContext and DbSet

Step-by-Step Guide to Using DbContext and DbSet in ASP.NET Core

Step 1: Set Up Your ASP.NET Core Project

  1. Open Visual Studio.
  2. Create a new project:
    • Select "ASP.NET Core Web App (Model-View-Controller)".
    • Name your project (e.g., DbContextExample).
    • Choose the .NET Core version and ASP.NET Core version.
  3. Click "Create".

Step 2: Install Entity Framework Core

  1. Right-click on your project in Solution Explorer and select Manage NuGet Packages.
  2. Search for Microsoft.EntityFrameworkCore.SqlServer and install it.
  3. Install Microsoft.EntityFrameworkCore.Tools for Entity Framework Core tools.

Step 3: Create a Model

Create a new class in a new file named Book.cs:

namespace DbContextExample.Models
{
    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
    }
}

Step 4: Create a DbContext

Create a new class named AppDbContext.cs:

using Microsoft.EntityFrameworkCore;
using DbContextExample.Models;

namespace DbContextExample.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        public DbSet<Book> Books { get; set; }
    }
}

Step 5: Configure DbContext in Startup.cs

Modify the Startup.cs file to register the DbContext with the dependency injection container:

using Microsoft.EntityFrameworkCore;
using DbContextExample.Data;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Configure DbContext
        services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

    public IConfiguration Configuration { get; }
}

Step 6: Add Connection String in appsettings.json

Add a connection string in appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=DbContextExampleDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Step 7: Create a Migration

Open the Package Manager Console in Visual Studio and run the following command to create a migration:

Add-Migration InitialCreate

Step 8: Apply the Migration

Run the following command to apply the migration and create the database:

Update-Database

Step 9: Create a Controller

Add a new controller named BooksController.cs:

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using DbContextExample.Data;
using DbContextExample.Models;

namespace DbContextExample.Controllers
{
    public class BooksController : Controller
    {
        private readonly AppDbContext _context;

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

        public IActionResult Index()
        {
            var books = _context.Books.ToList();
            return View(books);
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(Book book)
        {
            if (ModelState.IsValid)
            {
                _context.Add(book);
                _context.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            return View(book);
        }
    }
}

Step 10: Create Views for the Books Controller

Create a new folder named Books inside the Views folder. Then, create the following views:

  1. Index.cshtml:
@model IEnumerable<DbContextExample.Models.Book>

<h2>Books</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Title)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Author)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Author)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.BookId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.BookId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.BookId">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>
  1. Create.cshtml:
@model DbContextExample.Models.Book

<h2>Create</h2>

<form asp-action="Create">
    <div class="form-group">
        <label asp-for="Title" class="control-label"></label>
        <input asp-for="Title" class="form-control" />
        <span asp-validation-for="Title" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Author" class="control-label"></label>
        <input asp-for="Author" class="form-control" />
        <span asp-validation-for="Author" class="text-danger"></span>
    </div>
    <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" />
    </div>
</form>

Step 11: Run the Application

  1. Press F5 or click "Start" to run the application.
  2. Navigate to /Books to see the index page.
  3. You can create new books and see them listed.

Summary

In this example, you learned how to set up an ASP.NET Core project, configure Entity Framework Core, create a DbContext and DbSet, register the DbContext with the dependency injection container, create a controller and views, and perform basic CRUD operations.

Top 10 Interview Questions & Answers on ASP.NET Core DbContext and DbSet

Top 10 Questions and Answers on ASP.NET Core DbContext and DbSet

    • Answer: In ASP.NET Core, DbContext is a primary class that represents a session with the database. It's responsible for querying and saving instances of your entities to the database. It also acts as a bridge between your data model and the database by managing the connection, executing queries, and persisting changes.
  1. What is DbSet in DbContext?

    • Answer: DbSet<T> is a class that represents a collection of entities of a specific type. It corresponds to a table in your database. In the context of DbContext, DbSet provides methods for querying, adding, and removing entities. Each property of type DbSet<T> in your DbContext class represents a table in the database.
  2. How do you register DbContext in ASP.NET Core?

    • Answer: To register DbContext in ASP.NET Core, you typically use the AddDbContext<T>() method in the ConfigureServices method of your Startup.cs file or Program.cs if you're using .NET 6 or newer. For example:
      services.AddDbContext<AppDbContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
      
  3. How do you perform CRUD operations in ASP.NET Core DbContext and DbSet?

    • Answer:
      • Create: Add an entity to the DbSet collection and call SaveChanges() on the DbContext instance.
        context.Products.Add(new Product { Name = "New Product", Price = 29.99 });
        context.SaveChanges();
        
      • Read: Use LINQ or Query methods to query the DbSet.
        var product = context.Products.FirstOrDefault(p => p.Id == 1);
        
      • Update: Entity Framework Core will track changes to entities. Once you modify an entity, call SaveChanges().
        var product = context.Products.Find(1);
        product.Price = 34.99;
        context.SaveChanges();
        
      • Delete: Use Remove() on the DbSet and then SaveChanges().
        var product = context.Products.Find(1);
        context.Products.Remove(product);
        context.SaveChanges();
        
  4. What are the benefits of using Dependency Injection with DbContext?

    • Answer: Dependency Injection (DI) helps in managing the lifecycle of DbContext. It promotes loose coupling, better testability, and cleaner code. By registering DbContext with DI, you can inject DbContext into controllers or other services without manually creating and disposing of it, ensuring that the context is properly managed across request lifetimes.
  5. How does DbContext handle entity tracking?

    • Answer: DbContext automatically tracks changes to entities that it queries or adds to a DbSet. This is achieved through the ChangeTracker property, which keeps track of all entities added, modified, or deleted. When SaveChanges() is called, EF Core generates the SQL required to update the database based on the state of these entities.
  6. What is the RoleManager and UserManager in ASP.NET Core Identity using DbContext?

    • Answer: RoleManager and UserManager are services provided by ASP.NET Core Identity that utilize DbContext to manage users and roles. UserManager handles operations related to users, such as creating, updating, and deleting accounts, while RoleManager deals with role-related operations, like adding, updating, and deleting roles.
  7. What is the difference between Find and FirstOrDefault in DbContext?

    • Answer:
      • Find(): It's specifically for finding entities when the primary key is known. Find() checks the local cache first and, if the entity isn't found, queries the database. It's more efficient for lookups by primary key.
        var product = context.Products.Find(1);
        
      • FirstOrDefault(): It's a LINQ method that queries the data source as a sequence and returns the first element or a default value if no elements are found. It doesn't check the cache and always queries the database.
        var product = context.Products.FirstOrDefault(p => p.Id == 1);
        
  8. What is the purpose of the OnModelCreating method in DbContext?

    • Answer: The OnModelCreating method is overridden to configure the model that DbContext will use. This method provides a fine-grained way to configure the relationships between entities, such as foreign keys, and to specify details about the entities, like table names, column names, and data types. This configuration is often used when migrating the database schema to align with the data model.
  9. How do you handle exceptions when working with DbContext?

    • Answer: To handle exceptions in DbContext, you can use try-catch blocks around your database operations. This is important to manage database errors gracefully, provide user feedback, and maintain application stability. Additionally, it's a good practice to ensure that the Dispose() method is called on DbContext instances to release database connections, either manually or by using disposable patterns like using statements.

You May Like This Related .NET Topic

Login to post a comment.