'ObjectContext' vs 'DbContext' in Entity Framework

前端 未结 3 1914
南笙
南笙 2020-12-03 03:37

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 gu

3条回答
  •  温柔的废话
    2020-12-03 04:02

    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.

提交回复
热议问题