EF Core Migration Timeout: Step-by-Step Setup
In this article
Setting a timeout for Entity Framework Core migrations prevents long-running migration commands from failing due to the default 30-second command timeout. This is especially useful when applying migrations to large databases or during deployment in slow network environments. You can set the timeout globally in the DbContext options, per migration command, or via connection string. Below is a practical guide to configure it correctly.
What You'll Need
- An existing .NET project using Entity Framework Core (any version 2.0 or later).
- Access to the code where your DbContext is configured (usually in Startup.cs or Program.cs).
- If using the command-line tools, a terminal or command prompt with the .NET SDK installed.
Step-by-Step
- Identify where your DbContext options are configured. This is typically in
ConfigureServicesinStartup.cs(ASP.NET Core) or inProgram.csfor .NET 6+ using the minimal hosting model. Look for a call likeoptions.UseSqlServer(connectionString)or similar. - Add a command timeout to the DbContext options. Inside the
UseSqlServer(orUseNpgsql,UseMySql, etc.) call, add theCommandTimeoutoption. For example, to set a 5-minute timeout:
The value is in seconds. 300 seconds = 5 minutes. Choose a value that comfortably exceeds your longest expected migration.options.UseSqlServer(connectionString, sqlOptions => sqlOptions.CommandTimeout(300)); - Alternatively, set the timeout in the connection string. If you prefer not to modify code, add
Command Timeout=300to your connection string. For SQL Server, it looks like:
This works for most providers, but check your provider's documentation for the exact keyword (e.g.,Server=myserver;Database=mydb;User Id=myuser;Password=mypass;Command Timeout=300;Connection Timeoutis for the initial connection, not command execution). - For command-line migrations (dotnet ef), set the timeout via the
--connection-timeoutoption. When running commands likedotnet ef database update, you can pass the timeout in seconds:
This overrides the default for that specific command execution.dotnet ef database update --connection-timeout 300 - For migrations applied at runtime (e.g.,
context.Database.Migrate()), use the same DbContext options. The timeout set in step 2 applies automatically because the context uses the same configuration. - Verify the timeout is applied. To confirm, you can temporarily set a very short timeout (e.g., 1 second) and run a migration that takes longer. If it fails with a timeout error, the setting is working. Then restore the desired value.
Common Mistakes
- Setting
Connection Timeoutinstead ofCommand Timeout. The connection timeout only affects how long the initial connection attempt waits, not how long a command (like a migration) can run. - Using the wrong provider option. Some providers have different option names. For example, Npgsql uses
CommandTimeoutas well, but MySQL (Pomelo) usesCommandTimeouttoo. Always check the provider's documentation. - Forgetting that the timeout applies to all commands, not just migrations. If you set a very high timeout globally, regular queries will also wait longer, which can mask performance issues.
- Not applying the timeout to the design-time context. If you have a separate factory for design-time (e.g.,
IDesignTimeDbContextFactory), you must set the timeout there too, otherwise command-line migrations will still use the default.
Tips
- Use a value that is generous but not excessive. A common choice is 300 seconds (5 minutes) for typical migrations. For very large databases, consider 600 or 900 seconds.
- Test migrations in a staging environment first. Measure how long they take under realistic conditions, then set the timeout to at least double that time to allow for slow periods.
- Consider using a dedicated migration user with fewer permissions. This reduces risk, but the timeout setting is independent of permissions.
- If you use multiple environments (Development, Staging, Production), set the timeout via configuration. For example, read from
appsettings.jsonso you can adjust without code changes. - For CI/CD pipelines, pass the timeout as a parameter to the dotnet ef command. This keeps the pipeline self-documenting.
Troubleshooting
- Migration still times out after setting the timeout. First, verify the setting is actually being used. Check that you are modifying the correct DbContext instance. If you have multiple contexts, ensure the right one is being used. Also, check if the timeout is being overridden elsewhere (e.g., in a constructor or via
OnConfiguring). - Command-line migration ignores the timeout. If you set the timeout in the DbContext options but run
dotnet ef database update, it should pick it up. If not, ensure the design-time factory (if any) uses the same options. You can also explicitly pass--connection-timeoutto override. - Timeout error message says "Execution Timeout Expired". This is a SQL Server message. It means the command exceeded the timeout. Increase the value further or optimize the migration (e.g., split into smaller batches).
- Other commands in the app now take too long to fail. If you set a very high timeout globally, a stuck query will hold for that long. Consider setting a lower default and only increasing it for migrations via a separate context or by using a custom
ExecutionStrategy.
Frequently Asked Questions
Can I set a timeout for a single migration only?
Yes, but not directly in the migration code. You can run the migration command with a specific --connection-timeout for that execution. Alternatively, you can create a separate DbContext instance with a different timeout for that migration.
Does the timeout apply to the initial connection as well?
No, CommandTimeout only affects the execution of commands after the connection is established. To control the connection attempt, use Connection Timeout in the connection string (default is 15 seconds).
What is the default timeout in EF Core?
The default command timeout is 30 seconds, as defined by the underlying ADO.NET provider. This is often too short for migrations.
Will setting a longer timeout affect performance?
It only affects how long a command will wait before giving up. It does not speed up or slow down the actual execution. However, if a query hangs, it will hold resources longer, so use a reasonable value.
Can I set the timeout in the appsettings.json file?
Yes, you can store the timeout value in configuration and read it when configuring the DbContext. For example, add "MigrationTimeout": 300 to your config and use it in the options.
Does this work with PostgreSQL, MySQL, or other providers?
Yes, most providers support the CommandTimeout option, though the exact syntax may vary. Check the provider's documentation for the correct method name (e.g., CommandTimeout is common).