Search⌘ K

Disconnected Entities

Explore how to manage disconnected entities in Entity Framework Core, including adding, updating, and deleting data using separate DbContext instances. Understand how EF Core uses key values and entity states to synchronize changes with the database.

Overview

Previously, we saw how to retrieve and save entities using the same instance of a DbContext. This lesson reviews how to save disconnected entities. Disconnected entities refer to entities queried using one DbContext and saved using another DbContext.

The illustration above demonstrates attaching a disconnected entity to the context using the appropriate EntityState.

Note: The outputs from the projects in this lesson contain the results of the sample codes and logs from the translated SQL queries used.

Identifying new entities

Recall that EF Core automatically sets up value generation for primary keys. This feature is useful when determining if an entity needs to be inserted or updated. If a key has a value, then the entity was previously saved and now needs updating. Otherwise, it is new and requires inserting.

Adding single entities

The project below demonstrates adding single entities ...