Friday, September 9, 2016

Accessing ObjectContext from DbContext in Entity Framework


There are times, we need to work with ObjectContext. To get the ObjectContext we can cast it to the IObjectContextAdapter, which resides in the System.Data.Entity.Infrastructure namespace, and call the ObjectContext as follows.
using System.Data.Entity.Infrastructure;

using (var ctx = new YourDBEntities())
{
       var objectCtx = (ctx as IObjectContextAdapter).ObjectContext;
}

The other way is to create your own partial class and expose the ObjectContext as follows:

using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

public partial class YourDBEntities {

    public ObjectContext ObjectContext()
    {
        return (this as IObjectContextAdapter).ObjectContext;
    }
}

Then you can use with ease in all the places like:

using (var ctx = new SchoolDBEntities())
{
    var objectCtx = ctx.ObjectContext();
}

Inspired from Julie Lerman