Entity Framework Tutorial Basics(10):Entity Lifecycle

Entity Lifecycle:

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.

entity states in Entity

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.

转载于:https://www.cnblogs.com/purplefox2008/p/5648972.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值