Chapter 1: Introduction to Entity Framework Core and .NET 11
What You Will Learn
Explain what an ORM does and where EF Core sits between your C# code and SQL Server.
Create the book's work folder, pin the .NET SDK and create the Retail console project.
Define an entity, a DbContext and a DbSet.
Write a LINQ query and print the SQL EF Core plans for it, without a database.
Prerequisites
This chapter starts from an empty folder. You need the .NET 11 SDK and an editor, as About This Book describes. Nothing in this chapter connects to a database, so LocalDB can wait until Chapter 3. The companion's Chapter01 folder holds the finished project.
Concept Overview
By the end of this chapter, your Retail program prints a SQL Server query that finds every product with fewer than 5 items in stock, in Id order. You write the query in C#, as LINQ, and EF Core writes the SQL.
A C# program and a relational database hold the same data in different shapes. Your program works with objects: a Product with an Id, a Name and a StockQuantity. SQL Server stores rows in a Products table with columns of the same names. Code that moves data between the two by hand opens a connection, writes SQL text, reads each column of each row and copies it into a property. An object-relational mapper (ORM) does that work for you. Entity Framework Core (EF Core) is Microsoft's ORM for .NET.
In EF Core, a class that maps to a table is an entity, and Product is Retail's first one. You reach the database through a context: a class of your own that derives from EF Core's DbContext. The context knows the model (which entities exist and which tables they map to), and it offers each table as a DbSet property. db.Products is a DbSet<Product>, the starting point for querying products and for adding new ones.
A LINQ query on a DbSet does not run where you write it. db.Products.Where(p => p.StockQuantity < 5) returns an IQueryable<Product>: a description of the query that you can keep adding to. When you ask for results, for example with ToListAsync or a foreach loop, EF Core translates the description into SQL. The provider, a package that knows one database's dialect of SQL, writes that SQL for SQL Server and sends it. The rows come back, and materialization turns each row into a Product object (Figure 1.1).
The context also has a change tracker. It remembers the objects you loaded or added, and when you call SaveChanges it turns your changes into INSERT, UPDATE and DELETE statements. Chapter 5 shows it at work. This chapter uses ToQueryString, which asks EF Core for a query's SQL without running it, so you can see the translation before you have a database.
Figure 1.1. LINQ translation sends a SQL query through the SQL Server provider, and materialization turns the rows that come back into objects. SaveChanges sends the change tracker's INSERT, UPDATE and DELETE statements the same way.
Step-by-Step Implementation
Step 1: Create the Visual Studio solution and pin the SDK
Use Visual Studio 2026 for the Windows walkthrough. A solution groups related projects; a project chooses the .NET target, packages and files that build one program. Retail starts as one project and gains a separate test project in Chapter 12.
1. Choose File > New > Project, search for Blank Solution, select it and click Next. Name the solution EfCoreBook. Set Location to the folder where you keep projects, such as C:\Projects, and click Create. The resulting EfCoreBook folder is the book's work folder. Keep it outside a synced folder so synchronization cannot lock build output.
2. Open View > Solution Explorer if the solution tree is hidden. You should see Solution 'EfCoreBook' with no projects yet. Visual Studio saves this solution as EfCoreBook.slnx.
3. Open View > Terminal. The terminal is a PowerShell prompt inside the IDE. Check its current folder with Get-Location; use Set-Location with your own full path if it is not the folder that holds EfCoreBook.slnx.
4. Create the SDK selection file in that solution folder:
dotnet new globaljson --sdk-version 11.0.100 `
--roll-forward latestFeature
dotnet --version
The backtick continues a PowerShell command on the next line; on one line, leave it out. The first command reports that the global.json template was created. The second prints 11.0.100 or a later .NET 11 SDK you installed. global.json applies to the solution folder and every folder below it:
If you use VS Code instead, create and open an EfCoreBook folder, open Terminal > New Terminal and run the same commands there. The command-line equivalent of the empty solution is dotnet new sln --name EfCoreBook.
Step 2: Create Retail and install its packages
1. In Visual Studio, choose File > Add > New Project. Select the C# Console App template, not Console App (.NET Framework). Name it Retail and set Location to your existing EfCoreBook folder. Its project path should end in EfCoreBook\Retail\Retail.csproj.
2. Click Next, select .NET 11.0, keep top-level statements enabled and leave native AOT off, then click Create. Solution Explorer now shows Retail with Dependencies and Program.cs.
3. Press Ctrl+F5 to run without the debugger. The template prints Hello, World!. Close its console before changing the code. If Retail is not the startup project, right-click Retail and choose Set as Startup Project.
4. Right-click Retail and choose Manage NuGet Packages. On Browse, choose the nuget.org source, find Microsoft.EntityFrameworkCore.SqlServer, select version 11.0.0 and install it. Install System.Security.Cryptography.Pkcs version 10.0.13 the same way. Review any package-license dialog before accepting it. The Installed tab should show both references.
5. Double-click Retail in Solution Explorer to open Retail.csproj. Check the target and package versions against this file:
The SQL Server provider brings EF Core itself. The direct Pkcs reference pins its cryptography dependency to version 10.0.13. Keep NuGet's vulnerability auditing enabled and investigate any audit warning. Package references belong to Retail, not to the solution as a whole.
The project targets .NET 11 (net11.0), adds common using directives through ImplicitUsings and enables nullable reference warnings. Press Ctrl+Shift+B to build the solution; the Output window should report a successful build before you add the model.
The VS Code or terminal route creates the same project and references. Run these from the work folder:
For the rest of the book, a dotnet ef or dotnet run command normally runs in the Retail project folder, beside Retail.csproj. Solution Explorer can select Retail while the terminal is still in the solution folder; selecting a project does not move the terminal.
Step 3: Add the Product entity and the context
In Solution Explorer, right-click Retail and choose Add > New Folder to create Models and Data. Right-click Models, choose Add > Class and name it Product.cs. Replace the entire generated file with the listing, including any generated namespace line:
public sealed class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int StockQuantity { get; set; }
}
Product is an entity. EF Core treats a property named Id as the primary key and maps Name and StockQuantity to columns of the same names. The book's files leave out namespaces to stay short.
Use Add > Class on the Data folder to create InventoryDbContext.cs, then replace the entire generated file with:
using Microsoft.EntityFrameworkCore;
public sealed class InventoryDbContext(
DbContextOptions<InventoryDbContext> options)
: DbContext(options)
{
public DbSet<Product> Products => Set<Product>();
}
InventoryDbContext is Retail's context. Its primary constructor takes DbContextOptions<InventoryDbContext>, the settings that name the provider and the database, and passes them on to DbContext. Products is the DbSet for Product: Set<Product>() returns the context's set of products, and EF Core names the table Products after the property.
Step 4: Build a query and print its SQL
Replace Program.cs with:
using Microsoft.EntityFrameworkCore;
var options = new DbContextOptionsBuilder<InventoryDbContext>()
.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;" +
"Database=EfCoreBook_Retail;Integrated Security=true;" +
"TrustServerCertificate=true")
.Options;
using var db = new InventoryDbContext(options);
var threshold = 5;
var query = db.Products
.Where(p => p.StockQuantity < threshold)
.OrderBy(p => p.Id);
Console.WriteLine(query.ToQueryString());
DbContextOptionsBuilder builds the options by hand. UseSqlServer chooses the SQL Server provider and gives it a connection string, which says which server and database to use; Chapter 2 explains each part and moves it into a settings file. The @ makes a verbatim string, so the backslash in (localdb)\MSSQLLocalDB stays a backslash. using var db creates the context and disposes it when the program ends. A context is meant to live briefly: create it, do one piece of work, dispose it.
Where and OrderBy build an IQueryable<Product>, and nothing runs. ToQueryString asks the provider for the SQL it would send and returns it as text, without opening a connection. Save all files, build with Ctrl+Shift+B and run with Ctrl+F5. In the VS Code terminal, the equivalent is:
dotnet run
You should see:
DECLARE @threshold int = 5;
SELECT [p].[Id], [p].[Name], [p].[StockQuantity]
FROM [Products] AS [p]
WHERE [p].[StockQuantity] < @threshold
ORDER BY [p].[Id]
Read it from the top. The DECLARE line is the parameter: the value of threshold travels to SQL Server separately from the SQL text, so the same SQL works for any value and a value can never change the SQL. The SELECT line lists the columns for Product's three properties. FROM names the Products table and gives it the short alias p, which EF Core makes from the table name's first letter (renaming your lambda's parameter does not change it). The WHERE line is the predicate, the filter you wrote with Where, and ORDER BY comes from OrderBy. The program never connected to a database, so LocalDB did not have to be running.
Inspect the query in the Visual Studio debugger
Open Program.cs and click the left margin beside Console.WriteLine(query.ToQueryString());, or put the caret on that line and press F9. A red dot marks the breakpoint. Press F5. The yellow arrow shows the next statement; that statement has not run yet.
Open Debug > Windows > Locals and inspect threshold: it is 5. The query is still a description, not a list of products. Do not expand a query's Results View while investigating deferred execution: evaluating it can execute the query, and this chapter has not created a database. Press F10 to step over the WriteLine. The console shows SQL, and no database was opened. This is the last statement, so execution finishes after the context is disposed. Back in the editor, put the caret on the WriteLine and press F9 to remove the breakpoint.
Ask yourself what changed: you translated a query and printed text. You did not load products. Keeping those operations separate will help you diagnose the queries in Chapter 6.
Figure 1.2. The yellow arrow marks the next statement. Locals shows the threshold without executing the query.
Full Example
The chapter created global.json in the work folder and four files in the Retail folder.
public sealed class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public int StockQuantity { get; set; }
}
Data/InventoryDbContext.cs:
using Microsoft.EntityFrameworkCore;
public sealed class InventoryDbContext(
DbContextOptions<InventoryDbContext> options)
: DbContext(options)
{
public DbSet<Product> Products => Set<Product>();
}
Program.cs:
using Microsoft.EntityFrameworkCore;
var options = new DbContextOptionsBuilder<InventoryDbContext>()
.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB;" +
"Database=EfCoreBook_Retail;Integrated Security=true;" +
"TrustServerCertificate=true")
.Options;
using var db = new InventoryDbContext(options);
var threshold = 5;
var query = db.Products
.Where(p => p.StockQuantity < threshold)
.OrderBy(p => p.Id);
Console.WriteLine(query.ToQueryString());
Common Mistakes
Running a command in the wrong folder. dotnet new globaljson belongs in EfCoreBook; dotnet add package and dotnet run belong in Retail. Run in EfCoreBook, dotnet run reports that it cannot find a project.
Writing the connection string as a normal C# string with one backslash. \M is not a valid escape sequence, so the build fails. Use a verbatim string, as Program.cs does, or write \\.
Expecting a query to run where you write it. Where and OrderBy only describe the query. ToListAsync or a foreach loop runs it, and ToQueryString only shows its SQL.
Mixing EF Core versions. Keep every Microsoft.EntityFrameworkCore package at the same version, 11.0.0 in this book. EF Core 11 needs .NET 11.
Assuming every database behaves like SQL Server. Each provider translates queries, compares text and enforces rules its own way, so test against the database you deploy to.
Performance and Production Considerations
ToQueryString shows the SQL EF Core plans for a query; it is not a record of what ran. Chapter 6 adds dotnet run -- --ShowSql true, which prints every command the app sends, and Chapter 16 shows how SQL Server runs a query (its execution plan).
Keep filters (Where) and column choices (Select) in the query before ToListAsync, so SQL Server can return only the data you need. Some C# expressions cannot become SQL; Chapter 6 explains those limits. Work you add after ToListAsync runs on the fetched objects in your program.
EF Core suits business entities that you load, change and save, and queries you build up step by step. ADO.NET or a small SQL mapper gives you direct control over each command. Neither is faster for every workload, so measure a representative query before you change how an app reaches its data.
A provider's maturity, maintenance and license matter as much as its features. Check that its maintainer supports your EF Core version before you choose it. Cosmos DB, for example, has an EF Core provider but is a document database, not a relational one, so a relational model does not carry over unchanged.
Summary
An ORM maps classes to tables and LINQ queries to SQL. Retail now has a work folder pinned to the .NET 11 SDK, a console project with the SQL Server provider, one entity and a context with a DbSet. Where and OrderBy built a query, and ToQueryString printed its SQL without a database. Chapter 2 moves the connection string into a settings file and has a host create the context through dependency injection.
Key Terms
ORM (object-relational mapper): A library that maps classes to tables, turns queries written in code into SQL and copies rows into objects.
Entity: A class EF Core maps to a table, such as Product.
DbContext: The EF Core class your context derives from: a short-lived session that knows the model, runs queries and saves changes.
DbSet: A context property, such as Products, through which you query and add entities of one type.
Provider: The package that connects EF Core to one database engine and writes its SQL, such as Microsoft.EntityFrameworkCore.SqlServer.
IQueryable: The type a LINQ query on a DbSet returns. It describes the query, which runs when you ask for results.
ToQueryString: A method that returns the SQL a query would send, without running it.
Materialization: Turning the rows a query returns into objects.
Change tracker: The part of a context that remembers loaded and added objects and turns their changes into INSERT, UPDATE and DELETE statements when you call SaveChanges.
global.json: A file that tells the dotnet command which SDK version to use in its folder and every folder below it.
Mini Quiz
1. In the Retail project, what does query.ToQueryString() do?
A. Runs the query and prints the matching products
B. Creates the Products table if it does not exist
C. Returns the SQL EF Core would send for the query, without connecting to a database
D. Checks that LocalDB is running
2. What is db.Products in the Retail project?
A. A DbSet<Product>, the property you query and add products through
B. A List<Product> that is filled when the context is created
C. The connection string for the Products table
D. A view that SQL Server creates for the context
3. Which package provides the UseSqlServer method that Program.cs calls, and writes SQL Server's SQL?
A. System.Security.Cryptography.Pkcs
B. The console app template
C. global.json
D. Microsoft.EntityFrameworkCore.SqlServer
4. When a query runs, which part of EF Core turns the rows that come back into Product objects?
A. LINQ translation
B. Materialization
C. The change tracker
D. ToQueryString
5. Where do you run dotnet add package for the Retail project?
A. In the Retail folder, beside Retail.csproj
B. In the EfCoreBook folder, beside global.json
C. In the Models folder
D. In any folder, because a package is installed for the whole computer
A. A List<Product>; the database ran it on the Where line
B. A DbSet<Product>; it ran when the context was created
C. An IEnumerable<Product>; it never reaches the database
D. An IQueryable<Product>; it runs when you ask for results, for example with ToListAsync
Answers are provided in the Answer Key at the end of the book.
Activity
In File Explorer, create a new Activities/Chapter01 folder in your work folder and copy Retail into it as RetailActivity. Keep its project file named Retail.csproj. Open that copied project with File > Open > Project/Solution in Visual Studio; editing this copy must not change your main Retail project. Do not overwrite an earlier attempt; use another folder name for a repeat. Chapter 1 opens no database, so its connection string can stay as it is. Build the copied project. Any terminal command below runs in this RetailActivity folder, unless a bullet says otherwise. The companion's Activities/Chapter01/EfCoreBook.slnx opens its finished activity.
In the copy's Program.cs, change threshold to 10 and run dotnet run. You should see the DECLARE line end in = 10; while the SELECT, FROM, WHERE and ORDER BY lines stay the same: the value travels as a parameter, not inside the SQL text.
Build a second query that ends with .Select(p => new { p.Id, p.Name }) after OrderBy, and print its ToQueryString too. You should see a second SELECT that lists only [p].[Id] and [p].[Name]: a projection decides which columns SQL Server returns.
This second edition introduces Entity Framework Core through one growing Retail application. You should already know C# classes, LINQ, async methods, and basic SQL; previous ORM experience is not required.
Start with a console program, map the retail domain, and evolve the same project into a web API. The Windows walkthrough uses Visual Studio 2026 and SQL Server, with a VS Code alternative.
What you will learn
Map entities and relationships, and evolve the schema with migrations.
Query and page data while inspecting the SQL EF Core sends.
Protect concurrent edits and handle transactions.
Structure a read service and test data-access behavior.
Measure query performance and prepare deployment and diagnostics.
16 chapters include guided work, full examples, common mistakes, short quizzes with answers, and activities. Companion code is linked inside the book.
Release DateNovember 10, 2026
GenreSoftware & AI Development
ISBN979-8-90377-085-4
Read and listen on the go with the unQbd app.Get the app