Check if Entity is Removed

We implement the Entity Framework inside the winforms application using DbContext / Code First and have the following question regarding the correct check / handling method when the object was deleted / updated in a different context.

For example, we have some auxiliary table data (for example, StateCodes), and the user can go to another and add / remove states as necessary. This form of the auxiliary editor uses its own DbContext and saves the changes after the user exits the form. Upon returning to the main form, the main context does not know the changes made to the database, so we want to reload the DbSet for the object. Unfortunately, it seems that if we delete the “MI” status code, it still exists in the local DbSet property with EntityState unchanged even after we call “Load” to enable everything.

Outside of the complete removal of the main context, it would be best to check and verify whether any objects are deleted from the database?

foreach (State state in db.States.Local) { DbEntityEntry entry = db.Entry(state); DbPropertyValues databaseValues = entry.GetDatabaseValues(); if (databaseValues == null) { db.States.Remove(state); } else { entry.OriginalValues.SetValues(databaseValues); } } 

thanks for the help

+4
source share
2 answers

You should not keep the context live for your unit of work. The context should survive only as long as it is needed, otherwise you will certainly encounter caching traps, as you observe. (In addition, the context is really not so difficult when its instance, when you need it, is too laborious / resource-intensive).

If you really need to keep it alive, you may need to go to context in a helper form.

Reflected from my comment, thought this was the best answer

+3
source

First of all, what Brad said. Keep context only for a specific unit of work and delete it. Doing this will not lead to anything other than headaches.

You can also check the state of an object using the ObjectStateManager and pass the key of the object or entity. You can also use

public void Refresh( RefreshMode refreshMode, IEnumerable collection )

out of context. In addition, you can check the status of the recording.

http://msdn.microsoft.com/en-us/library/bb503718.aspx

0
source

All Articles