Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update DbSet.Local after row deletion in the database

I have a DbSet associated to a DbContext (with Entity Framework 4.3). The DbSet is initially loaded with all the entities of a given table X The problem is that I'm not able to Reload the DbSet to get a frech list of the table X after the deletion of one or several rows of that table (deletion done by another DbContext in another application).

Here is the line I'm using to reload all the entities of my table:

 ((IObjectContextAdapter) context).ObjectContext.Refresh(RefreshMode.ClientWins, col);

That line is working correctly for retrieving added entities or changed entities.

I also can not dispose the DbContext to get frech entities because my DbContext is also carrying another entities and it would be too long to reload them all (I know I'm not following the rule that say : DbContext should be used as a transnational objet)

like image 233
enenkey Avatar asked Dec 04 '25 13:12

enenkey


1 Answers

You can "clear" the Local collection and subsequently reload it:

foreach (var x in context.Set<X>().Local.ToList())
{
    Entry(x).State = EntityState.Detached;
}
context.Set<X>().Load();

You can't do context.Set<X>().Local.Clear();, because that marks all items in the collection as Deleted and the items will not be reloaded.

(Courtesy Code First: problem with Local collection).

like image 136
Gert Arnold Avatar answered Dec 07 '25 16:12

Gert Arnold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!