Sub topic 5
Choosing a Provider and Connection String
Your BloggingContext knows which tables exist. It still needs two more facts: what kind of database to use and where that database lives. This chapter shows you how to supply both.
What a Provider Is
A database provider is a NuGet package that lets EF Core talk to one specific database product. EF Core writes general instructions, and the provider turns them into the SQL dialect that its database understands.
Each provider gives you a method named Use... that switches it on.
| Database | Provider package | Method |
|---|---|---|
| SQLite | Microsoft.EntityFrameworkCore.Sqlite | `UseSqlite` |
| SQL Server | Microsoft.EntityFrameworkCore.SqlServer | `UseSqlServer` |
| PostgreSQL | Npgsql.EntityFrameworkCore.PostgreSQL | `UsePostgreSQL`-style `UseNpgsql` |
| MySQL | Pomelo.EntityFrameworkCore.MySql | `UseMySql` |
This tutorial uses SQLite. SQLite keeps the whole database in a single file, so you don't need to install or run a database server.
What a Connection String Is
A connection string is a short line of text that tells the provider how to reach the database. It is made of key=value pairs separated by semicolons.
For SQLite, one key is enough. Data Source names the database file:
Data Source=blogging.dbA server database needs more information, such as the server name, the database name, and login details:
Server=localhost;Database=Blogging;Trusted_Connection=True;TrustServerCertificate=TrueWiring It Up in OnConfiguring
OnConfiguring is a method on DbContext that EF Core calls when it sets up the context. You override it to choose the provider and pass in the connection string:
using Microsoft.EntityFrameworkCore;
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");
}options is a builder object. Calling UseSqlite on it tells EF Core to use the SQLite provider with this connection string.
To move to SQL Server later, you would install the SQL Server package and change that one line:
options.UseSqlServer(
"Server=localhost;Database=Blogging;Trusted_Connection=True;TrustServerCertificate=True");Your entity classes and queries stay the same. Being able to switch databases like this is one of the main benefits of an ORM.
Exercises
Exercise
What two things does the line options.UseSqlite("Data Source=blogging.db") tell EF Core?
Show answer
It tells EF Core to use the SQLite provider as the kind of database, and that the database lives in a file named blogging.db.
Exercise
You want to switch from SQLite to PostgreSQL. Which package do you add, and which method replaces UseSqlite?
Show answer
Add the Npgsql.EntityFrameworkCore.PostgreSQL package and call UseNpgsql with a PostgreSQL connection string. The entity classes and queries do not change.