实体生命周期【Entity Lifecycle】(EF基础系列10)

时间:2023-03-10 06:25:53
实体生命周期【Entity Lifecycle】(EF基础系列10)

Before we work on CRUD operation (Create, Read, Update, Delete), it's important to understand the entity lifecycle and how it is being managed by the EntityFramework.

During an entity's lifetime, each entity has an entity state based on the operation performed on it via the context (DbContext). The entity state is an enum of type System.Data.Entity.EntityState that includes the following values:

  1. Added
  2. Deleted
  3. Modified
  4. Unchanged
  5. Detached

The Context not only holds the reference to all the objects retrieved from the database but also it holds the entity states and maintains modifications made to the properties of the entity. This feature is known as Change Tracking.

The change in entity state from the Unchanged to the Modified state is the only state that's automatically handled by the context. All other changes must be made explicitly using proper methods of DbContext and DbSet.

The following figure illustrates how the operation performed on entity changes its' states which, in turn, affects database operation.

在我们进行增删查改操作之前,相当重要去理解实体的生命周期,它是怎么被EF操作的。

在实体的生命周期过程中,每个实体基于上下文的操作都会有一个实体状态,实体状态是一个枚举类型的值:System.Data.Entity.EntityState,包含下面的值:

1.Added

2.Deleted

3.Modified

4.Unchanged

5.Detached

数据上下文不仅包含所有从数据库中检索的对象的引用,并且它有这个实体对象的实体状态,维护修改实体的属性,这个特性叫做更改跟踪。

实体状态从“Unchaged”到“Modified”的改变是由数据上下文自动处理的,所以其他状态的改变,必须要使用DbContext和DbSet合适的方法.

下面的图表,列出了,改变实体状态的操作,反过来是怎么影响数据库的操作的。

实体生命周期【Entity Lifecycle】(EF基础系列10)

As you can see in the above figure, new entity in context has Added entity state. So the context will execute insert command to the database. In the same way, when you retrieve an existing entity using L2E queries, it will have Unchanged state, this is because you have just retrieved an entity and hasn't performed any operation on it yet. When you modify values of existing entity, it changes its state to Modified which in turn will execute update command on SaveChanges. Deleted entity from context will have Deleted state which in turn will execute delete command to the database.

So, in this way, operations performed on entities changes states. Context builds and executes database commands based on the state of an entity.

一个新的实体,保存的时候,生成的是Insert命令;

查询一个实体,实体的状态是Unchanged;

修改实体之后,再保存,就是Update;

删除就是Delete