We're implementing Entity Framework inside a winforms application using DbContext/Code First and have the following question regarding the proper way to check/handle when an entity has been deleted/updated in another context.
For example, we have some auxiliary table data (e.g. StateCodes) and the user could go in another and add/remove states as needed. This auxiliary editor form utilizes it's own DbContext and saves the changes once the user exits the form. Upon returning to the main form, the main context is unaware of the changes made to the database so we'd like to reload the DbSet for the entity. Unfortunately, it appears that if we remove the "MI" state code it still exists in the Local property of the DbSet with an EntityState of unchanged even after we call "Load" to bring in everything.
Outside of completely disposing of the main context would the following be the best way to check and see if what entities have been removed 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);
}
}
Thank you for your help
You shouldn't keep the context live past its unit of work. The context should only survive as long as its needed, otherwise you're bound to run in to caching pitfalls like you're observing. (Also, the context really isn't that heavy where instantiating it when you need it is overly time-consuming/resource intensive).
If you really must keep it alive, you may want to look in to passing the context to the auxiliary form.
Mirrored from my comment, figured it's best served as an answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With