Entity Framework Core Configuration

This document outlines the various ways to configure Entity Framework Core (EF Core) to tailor its behavior to your specific application needs. Configuration can be performed programmatically using the OnConfiguring method or externally via dependency injection.

1. Configuring EF Core with OnConfiguring

The simplest way to configure EF Core is by overriding the OnConfiguring method in your DbContext subclass. This method is called by EF Core when an instance of your context is created without explicit configuration being provided via dependency injection.

You can use OnConfiguring to:

  • Specify the connection string for your database.
  • Enable or disable logging.
  • Set various EF Core options.

Example: Using OnConfiguring


using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
        // Example of enabling logging to the console
        // optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public ICollection<Post> Posts { get; } = new List<Post>();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}
                
Tip: While OnConfiguring is convenient for simple scenarios, it's generally recommended to use dependency injection for more complex applications.

2. Configuring EF Core via Dependency Injection

The preferred method for configuring EF Core in modern .NET applications is through dependency injection. This allows for better separation of concerns and easier management of configuration in larger projects.

To configure EF Core via dependency injection, you typically:

  1. Register your DbContext with the service collection in your application's startup class.
  2. Provide the database connection string and other options during registration.

Example: Registering DbContext with Dependency Injection

In your Startup.cs (or equivalent in newer .NET versions, e.g., Program.cs):


using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration; // For accessing configuration

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Assuming you have a configuration object accessible
        // For example, from appsettings.json
        var connectionString = "Server=(localdb)\\mssqllocaldb;Database=Blogging;Trusted_Connection=True;";

        services.AddDbContext<BloggingContext>(options =>
            options.UseSqlServer(connectionString));

        // You can also configure logging here
        // services.AddDbContext<BloggingContext>(options =>
        //     options.UseSqlServer(connectionString)
        //            .LogTo(Console.WriteLine, LogLevel.Information));

        // Other service registrations...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...
    }
}
                
Note: The AddDbContext extension method is part of the Microsoft.EntityFrameworkCore.SqlServer package (or the appropriate package for your database provider).

Accessing the DbContext

Once registered, your DbContext can be injected into controllers, services, or other components that require it:


public class BlogsController : Controller
{
    private readonly BloggingContext _context;

    public BlogsController(BloggingContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        var blogs = _context.Blogs.ToList();
        return View(blogs);
    }
}
                

3. Configuring Database Providers

EF Core supports various database providers. You must install the appropriate NuGet package for your chosen database and use the corresponding extension method to configure it.

  • SQL Server: Microsoft.EntityFrameworkCore.SqlServer (UseSqlServer)
  • SQLite: Microsoft.EntityFrameworkCore.Sqlite (UseSqlite)
  • PostgreSQL: Npgsql.EntityFrameworkCore.PostgreSQL (UseNpgsql)
  • MySQL: Pomelo.EntityFrameworkCore.MySql (UseMySql)
  • Azure Cosmos DB: Microsoft.EntityFrameworkCore.Cosmos (UseCosmos)

Refer to the official EF Core documentation for the most up-to-date list of supported providers and their specific configuration details.

Important: Ensure you have the correct database provider package installed for your project.

4. Configuring Options

Beyond the database provider and connection string, EF Core offers a wide range of options that can be configured to fine-tune its behavior. These are passed to the DbContextOptionsBuilder.

Commonly Configured Options:

  • Logging: Control what EF Core logs and where it sends the logs.
  • Query Splitting: Control how queries are translated into SQL.
  • Change Tracking: Configure how EF Core tracks changes to entities.
  • Connection Resiliency: Enable automatic retries for transient database errors.
  • Execution Strategy: Define how EF Core handles retries for operations.

Example: Configuring Logging and Execution Strategy


services.AddDbContext<BloggingContext>(options =>
    options.UseSqlServer(connectionString)
           .EnableSensitiveDataLogging() // Logs parameter values (use with caution in production)
           .UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery) // Example of query splitting
           .EnableRetryOnFailure( // Enable retries for transient errors
               maxRetryCount: 5,
               maxRetryDelay: TimeSpan.FromSeconds(30),
               errorNumbersToAdd: null));
                

5. Configuring for Specific Scenarios

EF Core provides configurations for various specific scenarios, such as:

  • Batching: Optimize multiple save operations.
  • No-Tracking Queries: Improve read performance by disabling change tracking for queries that don't modify entities.
  • Interceptors: Hook into EF Core operations for custom logic.

Explore the advanced configuration topics in the EF Core documentation for these and other specialized needs.

This guide provides a foundational understanding of EF Core configuration. For detailed information on specific options and advanced techniques, please refer to the official Entity Framework Core documentation.