Attaching and Detaching Entities

本文介绍了如何在ObjectContext中管理实体对象状态,包括更新、断开连接和应用当前值的方法。通过实例演示了如何在对象上下文中操作Racer实体,并在断开连接后修改其属性。

If the entity object is already inside the object context, the existing one is used; otherwise it is fetched newly from the database.Invoking the method ApplyCurrentValues() passes the modified entity

object to the object context,and if there are changes, then the changes are done within the existing entity with the same key inside the object context, and the EntityState is set to EntityState.Modified. Remember that the method ApplyCurrentValues() requires the object to exist within the object context; otherwise the new entity object is added with EntityState.

private static void DetachDemo()
        {
            using (var data = new Formula1Entities())
            {
                data.ObjectStateManager.ObjectStateManagerChanged +=
                      ObjectStateManager_ObjectStateManagerChanged;
                ObjectQuery<Racer> racers = data.Racers.Where("it.Lastname='Alonso'");
                Racer fernando = racers.First();
                EntityKey key = fernando.EntityKey;
                data.Racers.Detach(fernando);
                // Racer is now detached and can be changed independent of the object context
                fernando.Starts++;
                Racer originalObject = data.GetObjectByKey(key) as Racer;
                data.Racers.ApplyCurrentValues(fernando);

                
            }

        }
static void ObjectStateManager_ObjectStateManagerChanged(object sender,
             CollectionChangeEventArgs e)
       {
           Console.WriteLine("Object State change—action: {0}", e.Action);
           Racer r = e.Element as Racer;
           if (r != null)
               Console.WriteLine("Racer {0}", r.Lastname);
       }

转载于:https://www.cnblogs.com/fast-michael/archive/2011/06/16/2082725.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值