C# tutorials > Frameworks and Libraries > Entity Framework Core (EF Core) > DbContext and DbSet (configuration, contexts)
DbContext and DbSet (configuration, contexts)
Entity Framework Core (EF Core) is an ORM (Object-Relational Mapper) that simplifies database interactions in .NET applications. DbContext and DbSet are fundamental components of EF Core. DbContext represents a session with the database, allowing you to query and save data. DbSet represents a collection of entities (database tables) within the DbContext. This tutorial provides a comprehensive guide to understanding and using DbContext and DbSet in EF Core.
DbContext: The Database Context
The DbContext class is the core of EF Core. It acts as a bridge between your application code and the underlying database. It's responsible for tracking changes to entities, managing database connections, and executing queries and commands. You typically create a class that inherits from DbContext and configure it with the necessary connection string and options.
Defining a DbContext
This code snippet demonstrates how to define a DbContext class called BloggingContext.  It inherits from DbContext and takes DbContextOptions in its constructor for configuration.  The DbSet and DbSet properties represent the Blogs and Posts tables in the database, respectively.
using Microsoft.EntityFrameworkCore;
public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options) : base(options)
    {
    }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}DbSet: Representing Database Tables
DbSet is a generic class that represents a collection of entities in the database. Each DbSet corresponds to a table in your database. You use DbSet properties within your DbContext to interact with specific tables.  These properties allow you to perform CRUD (Create, Read, Update, Delete) operations on the corresponding entities.
Configuring the DbContext
This code demonstrates how to configure the DbContext in your application's startup class (e.g., in an ASP.NET Core application).  It uses the AddDbContext method to register the BloggingContext with the dependency injection container.  The UseSqlServer method specifies that you are using SQL Server as the database provider and provides the connection string.  Replace "YourConnectionString" with your actual database connection string.
using Microsoft.EntityFrameworkCore;
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BloggingContext>(options =>
            options.UseSqlServer("YourConnectionString"));
    }
}Concepts Behind the Snippet
This snippet highlights the crucial concepts of DbContext and DbSet in EF Core. The DbContext is a session with the database, responsible for managing connections and tracking changes.  The DbSet represents a collection of entities, allowing you to interact with specific tables in the database.
Real-Life Use Case Section
Imagine you're building an e-commerce application. You'd have tables like Products, Customers, and Orders. Each of these would be represented as a DbSet in your DbContext.  You would use the DbContext to query products, create new customers, and manage orders.  For instance, you could retrieve a list of all products with a price greater than $50 using the Products DbSet.
Best Practices
Interview Tip
Be prepared to explain the roles of DbContext and DbSet in EF Core.  Understand how they facilitate database interactions and the importance of proper configuration.  Also, be ready to discuss best practices for using them effectively.
When to Use Them
Use DbContext and DbSet whenever you need to interact with a database using Entity Framework Core. They are essential for performing CRUD operations, querying data, and managing database changes.  If you are working with raw SQL queries or other data access technologies, you might not need them.
Memory Footprint
The memory footprint of DbContext depends on the size of the entities being tracked and the duration of the context's lifecycle.  Long-lived DbContext instances that track a large number of entities can consume significant memory.  It's crucial to keep the DbContext lifespan short and dispose of it properly to minimize memory usage. Using .AsNoTracking() on queries can also reduce memory consumption since the context doesn't track changes to the returned entities.
Alternatives
While DbContext and DbSet are fundamental to EF Core, alternatives for data access include Dapper (a micro-ORM), ADO.NET (for direct database interaction), and other ORMs like NHibernate. Each option has its own trade-offs in terms of performance, complexity, and features.
Pros
DbContext/DbSet provide a high level of abstraction over database interactions, making your code more readable and maintainable.
Cons
FAQ
- 
                        What is the difference betweenDbContextandDbSet?
 DbContextrepresents a session with the database, allowing you to query and save data.DbSetrepresents a collection of entities (database tables) within theDbContext. Think ofDbContextas the connection manager andDbSetas the table accessor.
- 
                        How do I configure the connection string for myDbContext?
 You can configure the connection string in the ConfigureServicesmethod of yourStartupclass (in ASP.NET Core applications) or in theOnConfiguringmethod of yourDbContext(less common). The preferred method is through dependency injection.
- 
                        How do I perform CRUD operations usingDbContextandDbSet?
 You can use the DbSetproperties to access and modify entities in the database. For example, to add a new blog, you would use_context.Blogs.Add(newBlog); _context.SaveChanges();To read blogs:_context.Blogs.ToList();To delete:_context.Blogs.Remove(blogToDelete); _context.SaveChanges();. Remember to callSaveChangesto persist the changes to the database.
