Accessing ObjectContext Features from EF 4.1 DbContext

 The Entity Framework 4.1 DbContext is a lightweight version of the EF ObjectContext. It’s simpler to work with thanks t a streamlined surface of properties and methods. It may be just what you’ve always been looking for.

But….

Once in a while you might want to use a random method of the ObjectContext that is not available in the DbContext. .

All is not lost. The EF team built a hook in for you so that you can actually get to the ObjectContext from DbContext. It’s not as simple as a propert however, it requires a bit of casting and more.

When I know I will want the occasional benefit of the ObjectContext, I simply create a property in my DbContext class so it’s easier to get to. 

Here’s what it looks like:

 

   public class MyContext: DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
       //other dbsets, ctor etc.

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

Now when I have an instance of the DbContext, I can use features of the ObjectContext on the fly:

 db.ObjectContext()…..

 

 

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

2 thoughts on “Accessing ObjectContext Features from EF 4.1 DbContext

  1. For using Entity SQL or Compiled queries the IObjectContextAdapter is very useful.

    For your scenario, it’s possible to use DbContext.Database.SqlQuery and DbContext.Database.ExecuteSqlCommand.

  2. @rene! LOL…. I will point that out and provide a better example. I didn’t even realize those were there. More digging! 🙂

    //update from julie …I simply removed that usage example but want to point out that you CANNOT use CompiledQueries with DbContext OR with the ObjectContext that you get to through the IObjectContextAdapter. Next version of .NET (.NET 4.5) will have better support for caching queries from either db or objectcontext

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.