A database provider lets Entity Framework Core target different database systems through provider-specific implementations while preserving the same high-level object-manipulation API. section 12.2.1
Set up a provider in an ASP.NET Core application by following these steps:
- Choose a database such as SQLite, PostgreSQL, Microsoft SQL Server, or MySQL. section 12.2 section 12.6
- Install the matching EF Core NuGet package and the EF Core design package. section 12.2.1
- Register the application's DbContext with dependency injection, select the provider with its Use* method, and supply a connection string. section 12.2.3
- Use migrations to keep the entity model and database schema synchronized. section 12.2 section 12.6
Registering SQLite
Install Microsoft.EntityFrameworkCore.SQLite, load DefaultConnection from configuration, and register the context with AddDbContext<AppDbContext>(options => options.UseSqlite(connString)). Replace UseSqlite with the appropriate Use* method when choosing another provider. section 12.2.1 section 12.2.3
Listing 12.1 Installing EF Core in an ASP.NET Core application
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework> #1
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference #2
Include="Microsoft.EntityFrameworkCore.SQLite" #2
Version="7.0.0" /> #2
<PackageReference #3
Include="Microsoft.EntityFrameworkCore.Design" #3
Version="7.0.0" > #3
<IncludeAssets>runtime; build; native; contentfiles; #4
Analyzers; buildtransitive</IncludeAssets> #4
<PrivateAssets>all</PrivateAssets> #4
</PackageReference>
</ItemGroup>
Inspect the project file to see the EF Core SQLite runtime package and design-time package installed for a .NET 7 application. section 12.2.1
Listing 12.4 Registering a DbContext with the DI container
using Microsoft.EntityFrameworkCore;
WebApplicationBuillder builder = WebApplication.CreateBuilder(args);
var connString = builder.Configuration #1
.GetConnectionString("DefaultConnection"); #1
Builder.Services.AddDbContext<AppDbContext>( #2
options => options.UseSqlite(connString)); #3
WebApplication app = builder.Build();
app.Run();
Inspect the registration pattern that connects configuration, the provider, the connection string, and the dependency-injection container. section 12.2.3
