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 Blogs and DbSet Posts 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

  • Keep DbContext Lifespan Short: Create a new instance of DbContext for each unit of work (e.g., a single request or operation). Avoid keeping a DbContext instance alive for extended periods, as this can lead to performance issues and unexpected behavior.
  • Use Dependency Injection: Register your DbContext with the dependency injection container to manage its lifecycle and make it easily accessible throughout your application.
  • Configure Connection Strings Securely: Store your connection strings in a secure configuration file or environment variable, and avoid hardcoding them directly in your code.

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

  • Abstraction: EF Core and DbContext/DbSet provide a high level of abstraction over database interactions, making your code more readable and maintainable.
  • Object-Relational Mapping: They handle the mapping between your object model and the database schema, reducing the amount of boilerplate code you need to write.
  • Change Tracking: EF Core automatically tracks changes to entities, simplifying the process of updating and deleting data.

Cons

  • Performance Overhead: The abstraction provided by EF Core can introduce some performance overhead compared to direct database access.
  • Complexity: EF Core can be complex to configure and use effectively, especially for advanced scenarios.
  • Learning Curve: There is a learning curve associated with understanding the concepts and features of EF Core.

FAQ

  • What is the difference between DbContext and DbSet?

    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. Think of DbContext as the connection manager and DbSet as the table accessor.

  • How do I configure the connection string for my DbContext?

    You can configure the connection string in the ConfigureServices method of your Startup class (in ASP.NET Core applications) or in the OnConfiguring method of your DbContext (less common). The preferred method is through dependency injection.

  • How do I perform CRUD operations using DbContext and DbSet?

    You can use the DbSet properties 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 call SaveChanges to persist the changes to the database.