How to set Entity Framework Core migration timeout?
You can set the timeout for migration only by setting the timeout on the context before calling the Migrations method:
using (var context = new DispatchingDbContext(_configuration))
{
context.Database.SetCommandTimeout(300);
await context.Database.MigrateAsync().ConfigureAwait(false);
}
Set timeout for migrations ef .netcore
You can do it also in the constructor of your database context class.
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
Database.SetCommandTimeout(150000);
}
The error message you are getting is for a Command timeout, not a connection timeout.
UPDATE
As mentioned by Pace in comments, since EF Core 2.0 you are able to use IDesignTimeDbContextFactory
to change the behaviour of your context when it is being created by tooling at design time such as happens with Migrations.
Create a separate class in your project that implements the IDesignTimeDbContextFactory
interface and use the DbContextoptionsBuilder
to configure the behaviour you want - in this case, setting the command timeout value to 600 seconds:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace EFCoreSample.Model
{
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);
}
}
}
Make sure that your existing DbContext
has a constructor that takes a DbContextOptions
object as a parameter:
public AdventureContext(DbContextOptions options) : base(options){}
When the tooling runs the migration, it looks first for a class that implements IDesignTimeDbContextFactory
and if found, will use that for configuring the context. Runtime behaviour is not affected.
Original Answer No Longer Applies
There is no way to set the CommandTimeout
on a context when using EF commands. But you can set it globally in the constructor, and then remove it later if you don't need to keep it:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
{
Database.SetCommandTimeout(150000);
}
}