chapter eleven

11 Going deeper into the DbContext

 

This chapter covers

  • How your application’s DbContext detects changes in tracked entities
  • Using the change tracking method in your DbContext to build an audit trail
  • Using raw SQL commands via the DbContext’s Database property
  • Finding the entities to database mapping using DbContext’s Model property
  • Using EF Core’s database connection resiliency

This chapter looks at the properties and methods available in the application’s DbContext. You’ve seen a few of these properties and methods before, such as the Add, Update, and Remove methods already covered in chapter 3, but in this chapter you dig deeper into how they work. You also look at some other properties and methods that haven’t been covered in earlier chapters. You will look at each method used to write to the database, ways to make saving data quicker, executing SQL commands directly on your database, and accessing and using your EF Core configuration information.

This chapter starts by looking at the DbContext properties for setting the State of an entity class are covered, including what to do if your call to SaveChanges is taking too long to run. But we’ll start with an overview of the four properties in the DbContext class, with pointers to coverage of their related features.

11.1  Overview of the DbContext class’s properties

11.2  Understanding how EF Core tracks changes

11.3  Looking at commands that change an entity’s State

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

11.3.2    The Remove method – deleting a row from the database

11.3.3    Modifying an entity class by changing the data in that entity class

11.3.4    Modifying an entity class by calling the Update method

11.3.5    The Attach method – start tracking an existing untracked entity class

11.3.6    Setting the State of an entity directly

11.3.7    TrackGraph—handling disconnected updates with relationships

11.4  SaveChanges and its use of ChangeTracker.DetectChanges

11.4.1     How SaveChanges finds all the State changes

11.4.2    What to do if ChangeTracker.DetectChanges is taking too long

Approach 1 - INotifyPropertyChanged – Use when DetectChanges is slow on a few entity classes

Approaches 2 and 3 are not covered- here is a summary

Approach 4 - Proxy change tracking supporting INotifyPropertyChanged and INotifyPropertyChanging

11.4.3    Using the entities’ State within the SaveChanges method

11.4.4    Catching entity class’s state changes via events

11.4.5    Triggering events when SaveChanges / SaveChangesAsync are called

11.4.6    Intercepting a call to SaveChanges / SaveChangesAsync

11.5  Using SQL commands in an EF Core application

11.5.1    FromSqlRaw/FromSqlInterpolated – using SQL in an EF Core query

11.5.2    ExecuteSqlRaw/ExecuteSqlInterpolated – executing a non-query command

11.5.3    Reload—useful after an ExecuteSqlCommand

11.5.4    GetDbConnection – running your own SQL commands