Get DbContext from Entity in Entity Framework Core

c# entity-framework entity-framework-core reflection

Question

Is there a way to get an instance of the DbContext an entity is being tracked by (if any)?

I found the following suggestion/solution for EF6 Get DbContext from Entity in Entity Framework

public static DbContext GetDbContextFromEntity(object entity)
{
    var object_context = GetObjectContextFromEntity( entity );

    if ( object_context == null )
        return null;

    return new DbContext( object_context, dbContextOwnsObjectContext: false );
}

private static ObjectContext GetObjectContextFromEntity(object entity)
{
    var field = entity.GetType().GetField("_entityWrapper");

    if ( field == null )
        return null;

    var wrapper  = field.GetValue(entity);
    var property = wrapper.GetType().GetProperty("Context");
    var context  = (ObjectContext)property.GetValue(wrapper, null);

    return context;
}

Is there a way to get this result in EF Core?

1
1
5/23/2017 11:45:31 AM

Accepted Answer

No. EF Core does not have lazy loading yet. If it had, then, a proxy generated from it would eventually have a reference to the DbContext that loaded it. As of now, there is no such reference.

1
1/27/2017 11:53:34 AM

Popular Answer

One could use dependency injection on the instance/entity at creation. To allow the owning dbcontext to be retrieved from the entity later.

eg

class Book
{
  public readonly DBContext _dbcontext;

  public Book(DBContext dbcontext)
  {
    _dbcontext = dbcontext;
  }

}


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