Caching EF domain objects: The ObjectContext insta

2019-08-07 23:28发布

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.

0条回答
登录 后发表回答