Saturday, 11 April 2020

Persistence in Entity Framework

There are two scenarios when persisting (saving) an entity to the database using Entity Framework: the Connected Scenario and the Disconnected Scenario.

Connected Scenario

In the connected scenario, the same instance of the context class (derived from DbContext) is used in retrieving and saving entities. It keeps track of all entities during its lifetime. This is useful in windows applications with the local database or the database on the same network.
Entity Framework tutorial 4.3 dbcontext
Pros:
  • Performs fast.
  • The context keeps track of all entities and automatically sets an appropriate state as and when changes occurr to entities.
Cons:
  • The context stays alive, so the connection with the database stays open.
  • Utilizes more resources.

Disconnected Scenario

In the disconnected scenario, different instances of the context are used to retrieve and save entities to the database. An instance of the context is disposed after retrieving data and a new instance is created to save entities to the database.
Entity Framework tutorial 4.3 dbcontext
The disconnected scenario is complex because an instance of the context doesn't track entities, so you must set an appropriate state to each entity before saving entities using SaveChanges(). In the figure above, the application retrieves an entity graph using Context 1 and then the application performs some CUD (Create, Update, Delete) operations using Context 2. Context 2 doesn't know what operation has been performed on the entity graph in this scenario.
This is useful in web applications or applications with a remote database.
Pros:
  • Utilizes less resources compared to the connected scenario.
  • No open connection with the database.
Cons:
  • Need to set an appropriate state to each entity before saving.
  • Performs slower than the connected scenario.

No comments:

Post a Comment