Caching EF domain objects: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

不想你离开。 提交于 2020-01-05 07:32:29

问题


I know this exception is caused by some properties being defined as virtual and therefore it's trying to load them lazily after the context has been disposed.

However, I don't want to load the entire object graph just to perform a fairly simple query. And if I try to cache the objects when the context is still alive, it tries to lazily load everything, and slows it down considerably.

Is there any way of performing the query, and then getting a disconnected result set, so that it doesn't try to lazily load things that I don't want it to? Or just turn of lazy loading for a specific query?

Here's the code I'm using:

return _cacheHelper.CacheGetOrInsert(CenterCacheKey, "tariffs", () => {
    using (var context = GetContext()) {
        return context.Tariffs
            .Include("Rates")
            .Include("Rates.Tiers")
            .Include("Rates.Tiers.Discounts")
            .Include("Discounts")
            .Include("Discounts.Regions")
            .ToList();
    }
});

EDIT

Ahh, just discovered context.Configuration.LazyLoadingEnabled = false; That seems to work.

来源:https://stackoverflow.com/questions/19681773/caching-ef-domain-objects-the-objectcontext-instance-has-been-disposed-and-can

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