Sub topic 5
Choosing a Provider and Connection String
Your DbContext knows which tables exist, but it still needs to know which database to talk to and where to find it. This chapter covers the two settings that answer those questions: the provider and the connection string.
What a Provider Is
A database provider is a NuGet package that teaches EF Core how to work with one kind of database. EF Core itself does not know any SQL dialect. The provider turns your LINQ queries into the SQL that your database understands. It also handles data types and opens connections.
Every database speaks a slightly different version of SQL. For example, SQLite uses LIMIT to return only a few rows, while SQL Server uses TOP. The provider deals with these differences so your C# code can stay the same.
Each provider adds an extension method that you call when you configure the context. For SQLite, that method is UseSqlite.
Common Providers
The table lists the providers you are most likely to meet.
| Database | NuGet package | Method to call | Good for |
|---|---|---|---|
| SQLite | Microsoft.EntityFrameworkCore.Sqlite | `UseSqlite` | Learning, small apps, desktop and mobile apps |
| SQL Server / Azure SQL | Microsoft.EntityFrameworkCore.SqlServer | `UseSqlServer` | Business apps on Windows or Azure |
| PostgreSQL | Npgsql.EntityFrameworkCore.PostgreSQL | `UseNpgsql` | Open-source server databases |
| MySQL / MariaDB | Pomelo.EntityFrameworkCore.MySql | `UseMySql` | Existing MySQL systems |
| In-memory | Microsoft.EntityFrameworkCore.InMemory | `UseInMemoryDatabase` | Quick experiments (not a real database) |
This tutorial uses SQLite. SQLite is a database engine that stores the whole database in one file on your disk. You don't need to install or run a server, so it is the easiest one to start with.
What a Connection String Is
A connection string is a line of text that tells the provider how to reach the database. It is a list of key=value pairs separated by semicolons.
Each database has its own keys. Here are typical examples:
| Database | Example connection string |
|---|---|
| SQLite | `Data Source=blogging.db` |
| SQLite (read-only) | `Data Source=blogging.db;Mode=ReadOnly` |
| SQL Server (LocalDB) | `Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True` |
| PostgreSQL | `Host=localhost;Database=blogging;Username=app;Password=secret` |
For SQLite, Data Source is the path to the database file. If the file does not exist, SQLite creates it the first time something writes to it.
Server databases need more information: the server name, the database name, and some way to log in.
How the Pieces Fit Together
Configuring the Context in OnConfiguring
In the previous chapter, your context set both values in one line:
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=blogging.db");OnConfiguring is a method EF Core calls once, when the context is first used. The options object collects settings. UseSqlite picks the provider, and the text inside it is the connection string.
Checking the Connection
This complete Program.cs shows which provider and connection string your context uses, then tests whether the database exists yet. It uses the Blog and Post classes from earlier chapters.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
Console.WriteLine($"Provider: {db.Database.ProviderName}");
Console.WriteLine($"Connection: {db.Database.GetConnectionString()}");
Console.WriteLine($"Can connect: {await db.Database.CanConnectAsync()}");
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
public List<Post> Posts { get; } = new();
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } = "";
public string Content { get; set; } = "";
public int BlogId { get; set; }
public Blog Blog { get; set; } = null!;
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs => Set<Blog>();
public DbSet<Post> Posts => Set<Post>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=blogging.db");
}Run it with dotnet run. You should see the provider name Microsoft.EntityFrameworkCore.Sqlite. "Can connect" may print False because the blogging.db file has not been created yet. The next chapter creates it with migrations.
Keeping the Connection String Out of Your Code
Writing the connection string directly in code works for a local SQLite file. Real server connection strings often contain a password, and passwords must never be saved in source code, because anyone who can read the code can then read them.
A simple fix is to read the value from an environment variable. An environment variable is a named setting stored by the operating system, outside your code. Replace OnConfiguring with this version:
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
var connectionString =
Environment.GetEnvironmentVariable("BLOGGING_CONNECTION")
?? "Data Source=blogging.db";
options.UseSqlite(connectionString);
}If BLOGGING_CONNECTION is set, EF Core uses it. If it isn't, the code falls back to the local file. You can try it from a terminal:
export BLOGGING_CONNECTION="Data Source=test.db"
dotnet runOn Windows PowerShell, use $env:BLOGGING_CONNECTION="Data Source=test.db" instead of export.
Gotchas to Watch For
Relative paths depend on where you run the app
Data Source=blogging.db is a relative path, which means the location depends on the folder the program runs from. If you run the app from a different folder, or from an IDE that uses the bin folder, SQLite creates a second, empty database somewhere else. If your data seems to disappear, check this first. You can use a full path such as Data Source=/home/me/data/blogging.db to avoid it.
Switching providers is not just one line
To move to SQL Server, you would run dotnet add package Microsoft.EntityFrameworkCore.SqlServer and change UseSqlite to UseSqlServer. That compiles, but migrations contain provider-specific SQL and data types. Migrations made for SQLite will not work on SQL Server, so you have to create new ones.
Backslashes in C# strings
SQL Server names like (localdb)\mssqllocaldb contain a backslash. In normal C# strings, a backslash starts an escape sequence. Use a verbatim string with @ in front:
var cs = @"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True";Exercises
Exercise
What two things does the line options.UseSqlite("Data Source=blogging.db") decide?
Show answer
UseSqlite chooses the provider (SQLite), and "Data Source=blogging.db" is the connection string that tells the provider which database file to open.
Exercise
You run your app from Visual Studio and later from a terminal in the project folder. The data you saved earlier seems to be gone. What is the most likely cause?
Show answer
The connection string uses a relative path, so each run created or opened a different blogging.db file in a different working folder. Use a full path, or always run from the same folder.
Exercise
Why should a PostgreSQL connection string containing Password=secret not be written directly in OnConfiguring?
Show answer
Anyone who can read the source code (or the Git history) could see the password. Read it from an environment variable or a secret store instead.
Exercise
Change the program so it uses a database file named demo.db without editing any C# code. What do you do?
Show answer
Set the environment variable before running, for example export BLOGGING_CONNECTION="Data Source=demo.db" and then dotnet run. The OnConfiguring method reads the variable instead of using the default.