1

这是我正在尝试做的事情:

//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
    ...
}

之后,我使用NewsItemsfrom HttpRuntime.Cache。我的问题是有时NewsItems仍附加到旧上下文中,我不确定如何正确分离它们。

我试过这样简单的事情:

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

但它似乎并没有正确地自行分离,并且我得到了使用同一实体的多个上下文的异常。

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

4

1 回答 1

0

你试过这个吗?

foreach (var NewsItem in NewsItems)
{
    ((IObjectContextAdapter) Work.Context).ObjectContext.Detach(NewsItem);
}
于 2013-08-21T10:15:36.600 回答