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:
- Added
- Deleted
- Modified
- Unchanged
- 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合適的方法.
下面的圖表,列出了,改變實體狀態的操作,反過來是怎么影響數據庫的操作的。
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
文章列表