concept SaveChanges in category .net

appears as: SaveChges, SaveChges
Entity Framework 4 in Action

This is an excerpt from Manning's book Entity Framework 4 in Action.

Suppose you have to create a form where the user can insert, edit, delete, and display an order. When the user inserts an order, you create an Order object and as many OrderDetail instances as there are details. Next, you instantiate the context that manages and coordinates the updates to the database. Finally, you invoke the AddObject method to notify the Orders entity set that the order must be inserted into the database. AddObject doesn’t communicate with the database; it only notifies the context about the persistence operation. The real operation on the database is triggered when the SaveChanges method is invoked.

7.1. Persisting entities with SaveChanges

Entity persistence is the process that stores entities data inside the database. Triggering this procedure is simple as invoking the SaveChanges method of the ObjectContext class (which is the class from which the OrderITEntities class in OrderIT inherits).

The following snippet shows an example of how to use SaveChanges to persist modifications made to a customer:

Using SaveChanges is easy. When it’s invoked, it internally iterates over the entities in the Modified, Deleted, and Added states, generates the appropriate SQL statements, and executes them against the database. In the next section, we’re going deeper into this subject.

SaveChanges performs all the plumbing required for persisting entities. Not only does it synchronize the state manager with the entities (as you learned in chapter 6), but it also detects dirty entities (entities in the Added, Modified, and Deleted states), starts the connection and the transaction with the database, generates the correct SQL and commits or rolls back everything depending on whether some exception occurred. Eventually, it removes deleted entities and sets added and modified ones to Unchanged. In the end, it’s a complex process that uses the database, the state manager, and SQL to accomplish its task, as you see in figure 7.1.

Figure 7.1. The steps performed by the SaveChanges method to persist entity state