首页 | 新闻 | 交流 | 问吧 | 文档 | 手册 | 下载 | 博客

Attaching and Detaching Entities

作者:  时间: 2011-06-16

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);
       }