EF Core Connection String — Complete Guide
In this tutorial, you'll learn about EF Core Connection String. We cover key concepts, practical examples, and best practices.
You hardcode the database connection string in your code, commit it to source control, and now your production credentials are exposed. Connection strings should be stored securely outside the application code.
Wrong
public class AppDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("Server=localhost;Database=MyDb;User=sa;Password=P@ssw0rd!");
}
}
Output: Works. But the credentials are in source code, visible in git history, and shared with everyone who has access to the repo.
Right
// appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDb;User=sa;Password=P@ssw0rd!"
}
}
// Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
For production, use secrets:
// Development: dotnet user-secrets set "ConnectionStrings:DefaultConnection" "..."
// Production: Environment variables or Azure Key Vault
// Using environment variable
options.UseSqlServer(
Environment.GetEnvironmentVariable("DB_CONNECTION_STRING"));
// Using Azure Key Vault
builder.Configuration.AddAzureKeyVault(new Uri(vaultUrl), credential);
Prevention
- Never hardcode connection strings — use
appsettings.jsonfor development. - Use
dotnet user-secretsfor local development credentials. - Use environment variables, Key Vault, or secrets management for production.
- Use
.gitignoreto excludeappsettings.*.local.jsonwith secrets. - Use
<a href="/design-patterns/builder/">builder</a>.Configuration.GetConnectionString("name")to read from config. - Consider using Managed Identity (Azure) or Windows Authentication instead of SQL auth.
- Rotate connection string secrets regularly.
Common Mistakes with core connection string
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Learn more about EF Core security at DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro