'ObjectContext' vs 'DbContext' in Entity Framework

ぃ、小莉子 提交于 2019-11-27 13:16:29
Massimiliano Peluso

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.

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;
    }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!