在数据库中删除行后更新DbSet.Local [英] Update DbSet.Local after row deletion in the database

查看:111
本文介绍了在数据库中删除行后更新DbSet.Local的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与DbContext关联的DbSet(使用Entity Framework 4.3)。
DbSet最初加载了给定表X的所有实体
问题是我无法重新加载DbSet来删除表X或X之后的表X的frech列表该表的几行(由另一个应用程序中的另一个DbContext删除)。

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.

我也无法处置DbContext以获取frech实体,因为我的DbContext也承载了另一个实体,并且重新加载它们都太长了(我知道我没有遵循这样的规则:DbContext应该用作跨国对象)

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)

推荐答案

您可以清除 本地集合,然后重新加载它:

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();

您不能执行 context.Set< X>()。Local .Clear(); ,因为这会将集合中的所有项目标记为已删除,并且不会重新加载这些项目。

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.

(由代码优先:本地集合有问题)。

这篇关于在数据库中删除行后更新DbSet.Local的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆