Entity Framework Core (EF Core) is a .NET object-relational mapping library. It represents relational database data as .NET objects and lets ASP.NET Core applications query that data through a database context service. It does not generate HTML or responses by itself. section 1.1.4 section 17.6
A typical ASP.NET Core setup has four parts:
- Add the EF Core design and database-provider packages. The examples use the SQL Server provider and the dotnet-ef tool. section 7.2.1
- Define model classes and a context class, then configure the context as a service with AddDbContext. UseSqlServer selects the provider; a connection string supplies the database connection. section 7.2.4 section 17.5
- Create and apply a migration to establish the database schema. section 17.0
- Inject the context into an endpoint, query a DbSet<T> with LINQ, and use the returned objects to produce a response. Add marks an object for storage; SaveChangesAsync performs the update. section 17.5.6
Listing 7.17 Configuring Entity Framework Core in the Program.cs file in the SportsStore folder
using Microsoft.EntityFrameworkCore;
using SportsStore.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<StoreDbContext>(opts => {
opts.UseSqlServer(
builder.Configuration["ConnectionStrings:SportsStoreConnection"]);
});
var app = builder.Build();
app.UseStaticFiles();
app.MapDefaultControllerRoute();
app.Run();
The Program.cs listing shows AddDbContext registering a context and UseSqlServer reading its connection string from application configuration. section 7.2.4
A stored calculation
A sum endpoint looks up a Calculation by its requested count. If none exists, it calculates the result, adds a record, and calls SaveChangesAsync. Requesting /sum/10 finds seeded data; requesting /sum/100 creates a record that later requests can find. Each request still issues a query: database storage is not a response cache. section 17.5.6
Watch the SQL rather than treating EF Core as a black box. LINQ queries can retrieve far more data than the response needs. In Blazor, a query held in an IEnumerable<T> property runs again when the property is read; rerendering a component can therefore issue repeated queries even when the event did not change data. Inspect command logs and control when queries execute. section 17.5 section 36.3.2



