问题
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)
回答1:
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).
来源:https://stackoverflow.com/questions/19662194/update-dbset-local-after-row-deletion-in-the-database