11 Going deeper into the DbContext

 

This chapter covers

  • Seeing 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 covered in chapter 3, but in this chapter, you’ll dig deeper into how they work. You’ll 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, and ways to execute SQL commands directly on your database. You’ll also look at accessing and using your EF Core configuration information.

This chapter discusses the DbContext properties for setting the State of an entity class, 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 into 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