Chapter 6. Understanding the entity lifecycle
This chapter covers
- Understanding entity states
- Understanding transitions between states
- Automatic and manual state changes
At this point in the book, you have two-thirds of the basics you need to implement Entity Framework–based data access code. You have learned how to create an object model, how to map it against the database using the EDM, how to perform queries to retrieve data, and how to transform data in objects. What you’re still missing is an understanding of the entity lifecycle and how to persist modifications made to an entity into the database. This chapter is about the first part of that: the entity lifecycle.
In this chapter, you’ll learn about the different states an entity can be in and what can be done in each one of them. This is a central subject because the changes you make to an entity affect its state, which in turn affects the way those modifications are later persisted.
Let’s start our discussion by analyzing the lifecycle of an entity and its several states.
During its lifetime, an entity has a state. Before looking at how to retrieve entity state, let’s take a look at what entity state is. The state is an enum of type System.Data.EntityState that declares the following values:
- Added—The entity is marked as added.
- Deleted—The entity is marked as deleted.
- Modified—The entity has been modified.
- Unchanged—The entity hasn’t been modified.
- Detached—The entity isn’t tracked.