Chapter 7. Persisting objects into the database

 

This chapter covers

  • Persisting modified objects into the database
  • Persisting complex object graphs into the database
  • Persisting with foreign-key and independent associations

Now that you know how to handle entity lifecycles, you’re ready to take the next step: persisting modifications made to objects into the database.

In this chapter, we’ll discuss how to insert, update, and delete entities in both connected and disconnected scenarios. We’ll cover single-object updates, such as a customer, and complex graph updates, such as an order and its details. By the end of this chapter, you’ll be able to manage updates through Entity Framework.

Note

In this chapter, we won’t be discussing topics like transaction and concurrency management. They get a chapter of their own—chapter 8.

Let’s start our discussion with how the persistence process works.

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:

C#

var customer = from c in ctx.Companies
               where c.Id == 1
               select c;
customer.Name = "new name";
ctx.SaveChanges();

VB

7.2. Persisting changed entities into the database

7.3. Persisting entities graphs

7.4. A few tricks about persistence

7.5. Summary