16

I'm using the DbContext class within code that I am creating that is based on the Generic Repositories and Unit of Work design patterns. (I am following the guidance here.) While working on this project I have encountered the ObjectContext class.

I've read quite a number of posts that discuss ObjectContext vs. DbContext. While some of what I've read makes sense, I still don't have a complete understanding of the differences and this leaves me wondering about my current implementation. Should I be using DbContext, ObjectContext or both? Is using one of these now considered an anti-pattern?

DavidRR
  • 18,291
  • 25
  • 109
  • 191
afr0
  • 848
  • 1
  • 11
  • 29
  • 1
    possible duplicate of [Is DbContext the same as DataContext?](http://stackoverflow.com/questions/3471455/is-dbcontext-the-same-as-datacontext) – bytebender Jun 14 '12 at 00:19
  • This is not a Decorator its a Composite pattern –  Dec 02 '12 at 17:41

3 Answers3

24

DbContext is just a wrapper around ObjectContext.

DbContext is just a set of APIs that are easier to use than the APIs exposed by ObjectContext.

Anyway, here you'll find a very simple Visual Studio template that uses the Repository Pattern and the Entity Framework.

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
  • 2
    check this [article](http://www.c-sharpcorner.com/UploadFile/ff2f08/objectcontext-vs-dbcontext/) for more – Shaiju T Oct 16 '15 at 15:44
-1

From ObjectContext VS DBContext.

Dbcontext can be defined as a lightweight version of the ObjectContext or we can say Dbcontext is a wrapper of ObjectContext and exposes only the common features that are really required in programming. We can also get a reference to the ObjectContext from then DbContext to use those features that are only supported in ObjectContext.

The following code could help to get an ObjectContext Object from an existing DbContext Object.

public class EntityDBContext: DbContext, IObjectContextAdapter
{
   ObjectContext IObjectContextAdapter.ObjectContext
   {
        get
        {
              var objectContext = (this as IObjectContextAdapter)
              if(objectContext != null)
                return (this as IObjectContextAdapter).ObjectContext;
              else
                return null;
        }
   }
}

Finally, DbContext is not a replacement of ObjectContext, but it is a simple alternative that builds on ObjectContext.

Hui Zhao
  • 655
  • 1
  • 10
  • 20
-2

We can cast a DBContext to type ObjectContext

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

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