Introduction
An application that works on a development machine but cannot connect to the database in production is often failing because it starts with different configuration, not because the EF Core query is incorrect. A wrong server name, database name, port, authentication mode, expired secret or exhausted connection pool may all appear behind a similar high-level error.
This lesson presents a systematic way to distinguish these failures. The goal is not to place a production connection string in source code or log the complete exception and configuration blindly. A reliable approach validates configuration, protects secrets, tests connectivity in a controlled way, records meaningful EF Core and ADO.NET failures, and applies retry policies only to genuinely transient problems.
1. Why do environments behave differently?
ASP.NET Core can load configuration from multiple providers. The general sequence includes appsettings.json, environment-specific files, user secrets, environment variables and command-line values. Later providers override earlier values. Therefore, an environment variable on the production server may contain a different connection string from the one visible in the project file.
The runtime environment also matters. DOTNET_ENVIRONMENT and ASPNETCORE_ENVIRONMENT influence behavior for Development, Staging and Production. When these values are not set, the default environment is production. Production should not expose detailed error pages, but it should enable appropriate monitoring and secure logging.
Incorrect and risky approach
var connectionString = "Server=prod-db;Database=Orders;User Id=sa;Password=VerySecretPassword;";This example embeds a secret in source code and assumes that the same connection details can be used for development, testing and production. Anyone with access to the repository may see the password, and changing it requires a code change and redeployment.
Corrected approach
var builder = WebApplication.CreateBuilder(args);var connectionString = builder.Configuration .GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException( "ConnectionStrings:DefaultConnection is missing.");builder.Services.AddDbContext<OrdersDbContext>(options => options.UseSqlServer(connectionString, sql => sql.EnableRetryOnFailure()));The application now receives its connection string from external configuration. Production secrets can be supplied through a secure secret store, a platform setting or an appropriate environment variable. .NET User Secrets is suitable for local development; production secrets should not be placed in source code or plain-text configuration files.
2. Validating a connection string safely
The first diagnostic step is checking whether the connection string exists. However, logging the complete string is unsafe. Limited metadata such as the server, database and authentication mode may be logged when appropriate, but passwords, access tokens and complete connection strings must not be written to logs.
public sealed record ConnectionInfo( string Server, string Database, bool IntegratedSecurity, bool Encrypt);static ConnectionInfo DescribeConnection(string connectionString){ var builder = new SqlConnectionStringBuilder(connectionString); return new ConnectionInfo( builder.DataSource, builder.InitialCatalog, builder.IntegratedSecurity, builder.Encrypt);}SqlConnectionStringBuilder helps detect malformed values early. Missing quotation marks, invalid keys or invalid Boolean values can be identified while the application starts. Even the returned metadata should be handled carefully and logged according to the production logging policy.
var info = DescribeConnection(connectionString);logger.LogInformation( "Database configuration is available. Server={Server}, Database={Database}, IntegratedSecurity={IntegratedSecurity}, Encrypt={Encrypt}", info.Server, info.Database, info.IntegratedSecurity, info.Encrypt);3. Separating connectivity failures from query failures
A SqlException raised during an API request may indicate that the application could not establish a connection, or that the connection succeeded but the SQL command failed. A controlled health check or readiness probe can help distinguish these cases.
Testing the database during application startup is not always appropriate. A temporary network interruption could prevent the application from starting at all and make deployment more difficult. A readiness health check, monitoring system and controlled diagnostic operation are often safer alternatives.
public sealed class DatabaseProbe(OrdersDbContext db){ public async Task<bool> CanConnectAsync(CancellationToken cancellationToken) { return await db.Database.CanConnectAsync(cancellationToken); }}CanConnectAsync provides a basic connectivity test, but it does not prove that migrations are current or that every application query will succeed. A more specific readiness check can execute a small, safe query.
public async Task<bool> IsReadyAsync(CancellationToken cancellationToken){ try { await db.Database.ExecuteSqlRawAsync("SELECT 1", cancellationToken); return true; } catch (Exception exception) { logger.LogError(exception, "Database readiness check failed."); return false; }}The exception is recorded for authorized operators, but the response should not expose the server, username or password to the client. The client receives a general unhealthy result while the diagnostic details remain in the monitoring system.
4. Common production connection failures
Wrong server or port
Development may use localhost, LocalDB or a Docker service name. Production may require a DNS name, a custom port or a private network address. Inside a container, localhost refers to the container itself, not automatically to the database server. For a “server not found” error, check DNS resolution, network access, firewall rules and port information separately.
Wrong database name
The server connection may succeed while the Initial Catalog or Database value points to the wrong database. Development and production database names may be similar, which makes this mistake easy to overlook. The database name can usually be recorded as non-secret metadata while diagnosing the problem.
Authentication mismatch
Windows Integrated Security, SQL username/password authentication, managed identity and provider-specific authentication are not interchangeable. The identity used by the production process must have the required database permissions. A “login failed” message should not automatically be interpreted as an incorrect password; account lockout, authentication mode, expired tokens and missing permissions can produce related failures.
Encryption and certificate failures
Current SQL client configurations increasingly rely on encrypted connections and certificate validation. In production, permanently disabling certificate validation is not a safe fix. Configure a trusted certificate chain and a server name that matches the certificate. Development-only shortcuts should not be copied into production.
Connection-pool exhaustion
Connections that are opened manually and not disposed, long-running operations or transactions that remain open too long can reduce the number of available pooled connections. EF Core and ADO.NET generally use pooling, but the lifetime of the DbContext and timely release of connections still matter.
await using var scope = serviceScopeFactory.CreateAsyncScope();var db = scope.ServiceProvider.GetRequiredService<OrdersDbContext>();await db.Orders.AsNoTracking().Take(10).ToListAsync(cancellationToken);Long-lived contexts, parallel operations and unnecessarily long transactions increase pressure on the pool. A scoped context per request and no concurrent operations on the same context provide a safer baseline.
5. Logging EF Core failures meaningfully and safely
EF Core integrates with the standard ASP.NET Core logging infrastructure. Categories and levels can be configured so that production logs remain useful without recording excessive SQL detail.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.EntityFrameworkCore.Database.Command": "Warning", "Microsoft.EntityFrameworkCore.Infrastructure": "Warning" } }}During development, inspecting SQL commands may be useful. However, EnableSensitiveDataLogging can place real user values in logs. It should be enabled only for controlled, short-lived diagnostics in a safe development environment.
if (builder.Environment.IsDevelopment()){ builder.Services.AddDbContext<OrdersDbContext>(options => options.UseSqlServer(connectionString) .EnableDetailedErrors());}A production exception handler should not return detailed exception text to the user. Instead, generate a correlation ID and return it to the client. The log entry can include the exception, environment, operation name and correlation ID without disclosing secrets.
6. A retry policy does not fix every failure
Transient network faults, short service interruptions and temporary failures in distributed environments such as Azure SQL can be handled with the SQL Server provider's execution strategy.
builder.Services.AddDbContext<OrdersDbContext>(options => options.UseSqlServer(connectionString, sql => sql.EnableRetryOnFailure( maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null)));Retries do not correct a wrong server name, incorrect password, missing database, insufficient permissions or a broken migration. Manual transactions also require special care when retries are enabled because the complete unit of work may need to be replayed. For large result sets, retry strategies may buffer results and increase memory usage.
7. A step-by-step diagnostic workflow
- Verify the environment: Which environment name is the application actually using?
- Identify the configuration source: Is the value coming from JSON, an environment variable or a secret store?
- Inspect non-secret metadata: Check server, database, encryption and authentication information safely.
- Test network access: Verify DNS, port, firewall and private-network connectivity.
- Verify the identity: Check database permissions for the process identity or managed identity.
- Run a basic connectivity test: Use
CanConnectAsyncorSELECT 1to separate connection and query failures. - Check the schema: If the connection works but a table is missing, consider the wrong database or unapplied migrations.
- Inspect pool and duration metrics: Look for long queries, open transactions and contexts that are not disposed.
- Add retries only where appropriate: Do not hide permanent configuration failures behind repeated attempts.
8. Short practice exercise
In the following scenario, the application works in development but produces “Login failed” in production. First inspect the flawed code:
var connection = configuration["ConnectionStrings:DefaultConnection"];logger.LogInformation("Connection: {Connection}", connection);await db.Database.MigrateAsync();This code has three problems: the configuration value may be null, sensitive information may be logged, and migrations are applied on every startup without a controlled deployment decision. Refactor it using these principles:
- Throw a clear exception when the configuration is missing.
- Log only safe connection metadata.
- Move migration execution to the deployment process or a controlled administrative command.
- Use a readiness test to verify connectivity safely.
- Investigate identity and permissions instead of retrying a permanent login failure.
The expected result is a diagnostic flow that can distinguish server, database, authentication and authorization problems without exposing the real password.
Conclusion
Reliable production database troubleshooting begins with classifying the failure correctly, not with randomly changing the connection string. Differences between environments and configuration providers, incorrect server or database values, authentication, network access, certificates, connection pools and EF Core query failures must be examined separately.
A dependable application keeps secrets outside source code, never logs a complete connection string, uses controlled health checks, records meaningful exceptions and applies measured retries only to transient failures. This makes production incidents faster to diagnose while protecting credentials and user data.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?tabs=visual-studio&view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings
- https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
- https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/extensions-logging
- https://learn.microsoft.com/en-us/ef/core/providers/sql-server/