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()…..