简体   繁体   中英

Zombie objects in Entity Framework

I create few entities in Entity Framework . They are automatically added.

Is it normal that MyEntity.CreateMyEntity automatically adds entity to the context? MyEntity.CreateMyEntity自动将实体添加到上下文是否正常?

Now, I want to save them but if they violate the database constraints I get exception, nothing is persisted -- RIGHT, BUT -- these objects remain in the ObjectContext which I do not want.

I tried to run that code as:

using (var t = new TransactionScope()) {
   ...create entities...
   try
   {
     context.SaveChanges();
     t.Complete();
     context.AcceptAllChanges();
   }
   catch
   {
      MessageBox.Show("Ooops");
   }
}

but even if I ran it in the transaction, these entities remain in the context.

What am I missing? 我想念什么? Do I have to remove them manually?

Another option to avoid unwanted objects without having to dispose the context is to manually detach them after you have committed the changes to the DB using Detach() :

You can detach objects from an object context when they are no longer required. To do this, call the Detach method. This reduces the amount of memory used.

context.Detach(yourEntity);

Be careful with related entities though, if your entity has related objects the related entities will not be detached automatically.

All changes remain in context until you delete those changes. Unsuccesful save wont cancel changes. What do you mean by CreateMyEntity? Changes are added to context when you use AddObject or when you reference them in Entities already added.

If something goes wrong(exception) - you must dispose context (because it is already wrong) and start over: create new datacontext, fetch needed data, create new entities and etc...

PS: or you can fix problems and save context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM