ASP MVC 4实体的全局DBContext缓存

时间:2013-08-21 07:19:05

标签: asp.net asp.net-mvc entity-framework dbcontext

以下是我要做的事情:

//Check if NewsItems exists in HttpRuntime.Cache
...

//If it does not, add the items to cahce
using (var Work = new UnitOfWork())
{
    var NewsItems=Work.Repository<NewsRepository>().GetTop10();
    //Store NewsItems in HttpRuntime.Cache
    ...
}

之后,我使用NewsItems中的HttpRuntime.Cache。我的问题是,有时候NewsItems仍然依附于旧的上下文,我不确定如何正确地解除它们。

我尝试过这样简单的事情:

foreach (var NewsItem in NewsItems) {
    Work.Context.Entry(NewsPost).State = System.Data.Entity.EntityState.Detached;    
}

但它似乎没有正确地解除附加,并且我使用相同的实体获得了多个上下文的例外。

我应该克隆实体吗?或者我应该以不同的方式去除我的实体?

1 个答案:

答案 0 :(得分:0)

你试过这个吗?

foreach (var NewsItem in NewsItems)
{
    ((IObjectContextAdapter) Work.Context).ObjectContext.Detach(NewsItem);
}