How to detach entity from context when you no longer have a context reference

c# caching datacontext entity-framework entity-framework-6


I'm pre-loading product data into my website because I want it to load once at application startup rather than only when it's requested and I need it to be quickly available. One approach to guarantee quick loading is to do this. In order to accomplish this, I eagerly load my product object along with a few additional entities and store them in memory.

Then, to retrieve my data, I have something like this:

public override IEnumerable<Product> Get()
    var result = _cacheManager.Get(PreLoadCacheKey) as IEnumerable<Product>;
    if (result != null)
        return result;

    return base.Get();

I'm having trouble because when I use dependency injection, I have no control over the scope of my data context (other than setting it to InstancePerRequest() and leaving it alone), which means that even after I cache my entities, they retain a reference to the original context.

Despite my efforts, I am unable to resolve the following:

 The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects. 

when attempting to connect a new entity I am adding to the database to one that was pulled from the cache.

Attempts I've made:

  1. Getting the data by means ofAsNoTracking()
  2. looping through all the outcomes prior to caching them andDetach ing them from the current context and, when they are retrieved from the cache, attaching them to the new context.

In a perfect world, I'd like to be able to detach a context from an entity from the side of the entity in order to check if the entity is currently associated to the context and, if not, to remove it from the old context and reattach it to the new one. According to what I've observed, the only way to separate it is to make a reference to the previous context, which I don't have.

Am I overlooking something simple?


I'd tie the entity to another context in this case:

var orderLine = order.Lines.FirstOrDefault(ol => ol.Product.Id == product.Id) ?? new SalesOrderLine();

orderLine.Price = price.Price;
orderLine.Product = product; //This is my cache'd entity.
orderLine.ProductPriceType = price.ProductPriceType;
orderLine.Quantity += qty;

order.Customer = customer;
order.Status = SalesOrderStatus.Current;


In order to work around this problem right now, I am forcibly loading an uncached version.

12/6/2014 8:11:17 PM

Popular Answer

12/6/2014 8:24:21 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow