Caution

This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

Configuring a DbContext

This article shows patterns for configuring a DbContext with DbContextOptions. Options are primarily used to select and configure the data store.

In this article

AddDbContext

This approach requires setting up and using dependency injection. See more reading below for information on how to do this.

Startup code
services.AddEntityFramework()
    .AddSqlite()
    .AddDbContext<BloggingContext>(options =>
        options.UseSqlite("Filename=./blog.db"));
Context code
public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
}
Application code (in ASP.NET MVC)
public MyController(BloggingContext context)
Application code (using ServiceProvider directly, less common)
using (var context = serviceProvider.GetService<BloggingContext>())
{
  // do stuff
}

Constructor argument

This approach can be used with or without dependency injection.

Context code
public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}
Application code (without DI)
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseSqlite("Filename=./blog.db");
using (var context = new BloggingContext(optionsBuilder.Options))
{
    // do stuff
}
Application code (with DI in ASP.NET MVC)
public MyController(BloggingContext context)
Test code
var optionsBuilder = new DbContextOptionsBuilder();
optionsBuilder.UseInMemoryDatabase();
using (var context = new BloggingContext(optionsBuilder.Options))
{
    // test
}

Tip

This works if there are additional constructor parameters besides ‘options’. Those additional parameters will be resolved from the DI container.

OnConfiguring

Caution

OnConfiguring occurs last and can overwrite options obtained from DI or the constructor. This approach does not lend itself to testing (unless you target the full database). See Combinations.

Context code
public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=./blog.db");
    }
}

Combinations

The three options above can be used in combination. When multiple options are provided, DbContext uses the following priorities to select options:

  1. OnConfiguring (highest priority)
  2. Constructor argument
  3. AddDbContext (lowest priority)

Options or services selected in higher priorities will overwrite options from lower priorities.

More reading