9 Going deeper into the DbContext

 

This chapter covers

  • How EF Core detects changes to an entity
  • Using change tracking to build an audit trail
  • Using raw SQL commands from EF Core
  • Inspecting EF Core’s database model
  • Using EF Core’s database connection resiliency

So far in this book, you’ve seen a wide range of EF Core commands available to you. This chapter digs deeper into the properties and methods available in the application’s DbContext. In some cases, I provide a more detailed explanation of commands in chapter 3, such as the Add, Update, and Delete methods. I also introduce methods that haven’t been covered, such as Attach and TrackGraph, that give you options on how to change the database data.

The EF Core’s DbContext class has a wide range of methods and features. After dealing with the methods and properties relating to adding, updating, or deleting data, you’ll explore numerous other topics. We’ll start with an overview of the three properties in the DbContext class, with pointers to coverage of their related features.

9.1 Overview of the DbContext class’s properties

The DbContext class has only three properties:

9.2 Understanding how EF Core tracks changes

9.3 Details on every command that changes an entity’s State

9.3.1 The Add command--inserting a new row in the database

9.3.2 The Remove command—deleting a row from the database

9.3.3 Modifying a tracked entity—EF Core’s DetectChanges

9.3.4 INotifyPropertyChanged entities—a different way of tracking changes

9.3.5 The Update method—telling EF Core that everything has changed

9.3.6 The Attach method—changing an untracked entity into a tracked entity

9.3.7 Setting the State of an entity directly

9.3.8 TrackGraph—handling disconnected updates with relationships

9.4 Using ChangeTracker to detect changes

9.5 Using raw SQL commands in EF Core

9.5.1 FromSql—adding raw SQL to an EF Core query

9.5.2 ExecuteSqlCommand—executing a nonquery command

9.5.3 Reload—useful after an ExecuteSqlCommand

9.5.4 GetDbConnection—calling database access commands

9.6 Using Context.Model to access EF Core’s view of the database

9.6.1 Using the Model property to build a fast database wipe method

9.7 Handling database connection problems

9.7.1 Handling database transactions with EF Core’s execution strategy

9.7.2 Altering or writing your own execution strategy

Summary