No Detach() function on DbContext in Entity Framework code first

code-first entity-framework

Question

I'm curious as to why the DbContext object doesn't include a Detach function as the ObjectContext does. I can only presume that this omission was deliberate, but I'm having trouble understanding why. I must be able to separate and reassociate entities (for putting in the cache in an ASP.NET project, for example). The "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" problem occurs when I attempt to attach an entity that was connected to a prior context, however, since I am unable to remove an entity.

What's the advice in this case? Am I overlooking something?

1
62
11/12/2010 7:49:18 PM

Accepted Answer

For anyone who may come into this query, as of CTP5, you must now write

((IObjectContextAdapter)context).ObjectContext

to access the ObjectContext.

85
12/8/2010 10:09:36 AM

Popular Answer

In order to access or expose the necessary functionality from a derived DbContext, which uses an ObjectContext internally, the EF team makes this information available as a protected property just in case you ever need to use a lower level API.

public class YourContext : DbContext 
{
    public void Detach(object entity) 
    {
        ObjectContext.Detach(entity);            
    }
}

Then, to disconnect an entity, use this method from your controller.

As an alternative, you might modify it to have an even richer API:

public class YourContext : DbContext
{
    public void ChangeObjectState(object entity, EntityState entityState)
    {
        ObjectContext.ObjectStateManager.ChangeObjectState(entity, entityState);
    }
}

Here is how the metadata for DbContext looks:

public class DbContext : IDisposable 
{      
    protected System.Data.Objects.ObjectContext ObjectContext { get; }
    ...
}


Related Questions





Related

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