Setup DbContext
Add database provider package
To connect to specific database, you should pick one package to do that. Generally that provider package implicitly installs Microsoft.EntityFrameworkCore
.
For example, if you're using MSSQL:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
or PostgreSQL:
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
Inherit from DbContext
The abstraction of rows are usually presented as a DbSet<T>
where T
must be a class
using Microsoft.EntityFrameworkCore;
public class MoviesContext : DbContext
{
public DbSet<Movie> Movies { get; set; } // nullable warning goes here
}
2
3
4
5
6
While nullable warning may shows here, so you can use DbContext.Set<T>()
instead to softly remove the warning.
using Microsoft.EntityFrameworkCore;
public class MoviesContext : DbContext
{
public DbSet<Movie> Movies => Set<Movie>();
}
2
3
4
5
6
INFO
DbSet<T>
is IQueryable
, so all operations are lazy.
Setup database provider
EFCore needs to know which database engine it'll work with. The provider comes from the certain package you'll need to install. For example, use Microsoft.EntityFrameworkCore.SqlServer
if you're working with MSSQL; Use Npgsql.EntityFrameworkCore.PostgreSQL
to work with PostgreSQL. There's always a nuget package fits the database you use.
To setup database provider, an virtual empty method DbContext.OnConfiguring
exists to do the job.
// source code of DbContext
public class DbContext :
IInfrastructure<IServiceProvider>,
IDbContextDependencies,
IDbSetCache,
IDbContextPoolable
{
// ...other memebers
protected internal virtual void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } // yes it's empty
}
2
3
4
5
6
7
8
9
10
There'll be an extension method injected from the provier package to the DbContextOptionsBuilder
public class MoviesContext : DbContext
{
public DbSet<Movie> Movies => Set<Movie>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connectionString = "...";
optionsBuilder.UseSqlServer(connectionString); // use MSSQL here
base.OnConfiguring(optionsBuilder);
}
}
2
3
4
5
6
7
8
9
10
Injection
Lastly, inject your DbContext
.
/* Program.cs */
builder.Services.AddDbContext<MoviesContext>();
// ...
var app = biulder.Build()
// ...
2
3
4
5
No existing database?
If don't have your database implemented yet, you can create it by mapping using EntityFrameworkCore.
// Program.cs
var scope = app.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<MoviesContext>();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
2
3
4
5
For each time you launch the program, EntityFrameworkCore ensures the schema of the database by mapping. We haven't introduce any mapping yet, we'll discuss them later.
WARNING
Don't use it in production code base!