Extending the Command Timeout in Entity Framework Core Migrations

Most migrations that you execute when working with Entity Framework Core are likely to be straightforward - resulting in nothing more than an adjustment to the database schema. Sometimes, however, you might also want to include a task that requires longer than the default command timeout value (30 seconds in SQL Server) such as importing a lot of data.

Prior to version 2.0 of EF Core, your options were limited to changing the command timeout for the DbContext, running the migration and then resetting the timeout value (or not):

public SampleContext()
{
    Database.SetCommandTimeout((int)TimeSpan.FromMinutes(5).TotalSeconds);
}

The IDesignTimeDbContextFactory was introduced in EF Core 2.0 to alleviate this (and other) problems associated with configuring DbContext objects differently for certain design-time tasks, such as migrations.

This interface is only intended for use with design time tools such as migrations. The tools are configured to search the assembly containing the DbContext (or the one designated as the startup assembly) for a type that implements the interface. If one exists, it is instantiated and its CreateDbContext method is called which returns the derived DbContext - enabling you to configure the context in a different manner to the way it is configured for runtime use. As such, it provides a hook for overriding the construction of the DbContext type.

The following example illustrates the use of IDesignTimeDbContextFactory to override the creation of SampleContext, specifying a command timeout value of 10 minutes, as opposed to the default 30 seconds, or whatever value has been specified for the runtime version of the context:

public class SampleContextFactory : IDesignTimeDbContextFactory<SampleContext>
{
    public SampleContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<SampleContext>();
        optionsBuilder.UseSqlServer(
            @"Server=.\;Database=db;Trusted_Connection=True;", 
            opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds)
            );

        return new SampleContext(optionsBuilder.Options);
    }
}

Finally, you must ensure that your context has a constructor that takes a DbContextOptions object as a parameter:

public SampleContext(DbContextOptions options) : base(options) { }

It should be noted at this stage that the string[] args parameter on the CreateDbContext method is not currently implemented. Decisions have yet to be made on how arguments can be passed to this method via the various design-time tools that discover types that implement the interface.