Error message
Microsoft.Data.SqlClient.SqlException (0x80131904): Database <database_name> on server <database_server> is not currently available. Please retry the connection later.
This error message is displayed when the database connection parameters are correct, the service principal is authorized to access the database but the database is currently offline.
Context
- The serverless compute tier for Azure SQL automatically pauses databases during inactive periods . This means that the unavailable database is in a paused state.
- The database auto-resumes on certain conditions , including when the database is accessed.
Solution
Enable automatic retries when configuring the DbContext object
Retry support is provided by Entity Framework Core through the EnableRetryOnFailure option.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=EFMiscellaneous.ConnectionResiliency;Trusted_Connection=True;",
options => options.EnableRetryOnFailure());
}
The first attempt at connecting to the database server fails because the database server is in a paused state. However, this attempt triggers the auto-resume process. When the connection is retried about 500ms later, it’s successful because the database server is no longer in a paused state.