Update DbSet.Local after row deletion in the database

雨燕双飞 提交于 2020-01-04 04:02:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!