ef之 entitystate状态

之前使用EF,我们都是通过调用SaveChanges方法把增加/修改/删除的数据提交到数据库,但是上下文是如何知道实体对象是增加、修改还是删除呢?答案是通过EntityState枚举来判断的,我们看一个方法:

/// <summary>
        /// 查看实体状态
        /// </summary>
        private static void GetOneEntityToSeeEntityState()
        {
            using (var context = new DbContexts.DataAccess.BreakAwayContext())
            {
                var destination = context.Destinations.Find(4);
                EntityState stateBefore = context.Entry(destination).State;
                Console.WriteLine(stateBefore);
            }
        }

注:使用EntityState需添加引用system.data     
跑下程序,输出结果为:Unchanged。从英文意思我们已经猜到一二:取出来的数据是Unchanged,那么添加、修改、删除自然也就是Added、Modified、Deleted了。我们在EntityState上按F12定位到其定义看看:  

bubuko.com,布布扣  

的确,当调用SaveChanges方法的时候,EF会根据EntityState这个枚举检测到实体的状态,然后执行相应的增/删/改操作。它们的具体意思分别为:

  • An entity can be in one of five states as defined by the EntityState enumeration. These states are:

    • Added: the entity is being tracked by the context but does not yet exist in the database
    • Unchanged: the entity is being tracked by the context and exists in the database, and its property values have not changed from the values in the database
    • Modified: the entity is being tracked by the context and exists in the database, and some or all of its property values have been modified
    • Deleted: the entity is being tracked by the context and exists in the database, but has been marked for deletion from the database the next time SaveChanges is called
    • Detached: the entity is not being tracked by the context【database may be not existed】

    SaveChanges does different things for entities in different states:

    • Unchanged entities are not touched by SaveChanges. Updates are not sent to the database for entities in the Unchanged state.
    • Added entities are inserted into the database and then become Unchanged when SaveChanges returns.
    • Modified entities are updated in the database and then become Unchanged when SaveChanges returns.
    • Deleted entities are deleted from the database and are then detached from the context.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值