http://www.entityframeworktutorial.net/EntityFramework4.3/dbcontext-vs-objectcontext.aspx

As you have seen in the previous Create Entity Data Model section, EDM generates the SchoolDBEntities class, which was derived from theSystem.Data.Entity.DbContext class, as shown below.

The class that derives DbContext is called context class in entity framework.

Prior to EntityFramework 4.1, EDM used to generate context classes that were derived from the ObjectContext class.

It was a little tricky to work with ObjectContext. DbContext is conceptually similar to ObjectContext.

It is a wrapper around ObjectContext which is useful in all the development models: Code First, Model First and Database First.

DbContext is an important part of Entity Framework.

It is a bridge between your domain or entity classes and the database.

DbContext is the primary class that is responsible for interacting with data as object.

DbContext is responsible for the following activities:

  • EntitySet: DbContext contains entity set (DbSet<TEntity>) for all the entities which is mapped to DB tables.
  • Querying: DbContext converts LINQ-to-Entities queries to SQL query and send it to the database.
  • Change Tracking: It keeps track of changes that occurred in the entities after it has been querying from the database.
  • Persisting Data: It also performs the Insert, Update and Delete operations to the database, based on what the entity states.
  • Caching: DbContext does first level caching by default. It stores the entities which have been retrieved during the life time of a context class.
  • Manage Relationship: DbContext also manages relationship using CSDL, MSL and SSDL in DB-First or Model-First approach or using fluent API in Code-First approach.
  • Object Materialization: DbContext converts raw table data into entity objects.

The following is an example of SchoolDBEntities class (context class that derives DbContext) generated with EDM for SchoolDB database in the previous section.

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq; public partial class SchoolDBEntities : DbContext
{
public SchoolDBEntities()
: base("name=SchoolDBEntities")
{
} protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
} public virtual DbSet<Course> Courses { get; set; }
public virtual DbSet<Standard> Standards { get; set; }
public virtual DbSet<Student> Students { get; set; }
public virtual DbSet<StudentAddress> StudentAddresses { get; set; }
public virtual DbSet<Teacher> Teachers { get; set; }
public virtual DbSet<View_StudentCourse> View_StudentCourse { get; set; } public virtual ObjectResult<GetCoursesByStudentId_Result> GetCoursesByStudentId(Nullable<int> studentId)
{
var studentIdParameter = studentId.HasValue ?
new ObjectParameter("StudentId", studentId) :
new ObjectParameter("StudentId", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetCoursesByStudentId_Result>("GetCoursesByStudentId", studentIdParameter);
} public virtual int sp_DeleteStudent(Nullable<int> studentId)
{
var studentIdParameter = studentId.HasValue ?
new ObjectParameter("StudentId", studentId) :
new ObjectParameter("StudentId", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_DeleteStudent", studentIdParameter);
} public virtual ObjectResult<Nullable<decimal>> sp_InsertStudentInfo(Nullable<int> standardId, string studentName)
{
var standardIdParameter = standardId.HasValue ?
new ObjectParameter("StandardId", standardId) :
new ObjectParameter("StandardId", typeof(int)); var studentNameParameter = studentName != null ?
new ObjectParameter("StudentName", studentName) :
new ObjectParameter("StudentName", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Nullable<decimal>>("sp_InsertStudentInfo", standardIdParameter, studentNameParameter);
} public virtual int sp_UpdateStudent(Nullable<int> studentId, Nullable<int> standardId, string studentName)
{
var studentIdParameter = studentId.HasValue ?
new ObjectParameter("StudentId", studentId) :
new ObjectParameter("StudentId", typeof(int)); var standardIdParameter = standardId.HasValue ?
new ObjectParameter("StandardId", standardId) :
new ObjectParameter("StandardId", typeof(int)); var studentNameParameter = studentName != null ?
new ObjectParameter("StudentName", studentName) :
new ObjectParameter("StudentName", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("sp_UpdateStudent", studentIdParameter, standardIdParameter, studentNameParameter);
}
}

As you can see in the above example, context class (SchoolDBEntities) includes entity set of type DbSet<TEntity> for all the entities.

Learn more about DbSet class here. It also includes functions for the stored procedures and views included in EDM.

Context class overrides OnModelCreating method.

Parameter DbModelBuilder is called Fluent API, which can be used to configure entities in the Code-First approach.

Instantiating DbContext:

You can use DbContext by instantiating context class and use for CRUD operation as shown below.

using (var ctx = new SchoolDBEntities())
{ //Can perform CRUD operation using ctx here..
}

Getting ObjectContext from DbContext:

DBContext API is easier to use than ObjectContext API for all common tasks. However, you can get the reference of ObjectContext from DBContext in order to use some of the features of ObjectContext. This can be done by using IObjectContextAdpter as shown below:

using (var ctx = new SchoolDBEntities())
{
var objectContext = (ctx as System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext; //use objectContext here..
}

EDM also generates entity classes. Learn about the different types of entity in the next chapter.

DBContext的更多相关文章

  1. EntityFramework Core 1.1是如何创建DbContext实例的呢?

    前言 上一篇我们简单讲述了在EF Core1.1中如何进行迁移,本文我们来讲讲EF Core1.1中那些不为人知的事,细抠细节,从我做起. 显式创建DbContext实例 通过带OnConfiguri ...

  2. Entity Framework 教程——DBContext

    DBContext: 在之前的章节<创建实体数据模型>中,EDM为我们创建了SchoolDBEntities 类,它派生子System.Data.Entity.DbContext这个类,这 ...

  3. [译]DbContext API中使用SqlQuery和ExecuteSqlCommand获取存储过程的输入输出参数

    水平有限,欢迎指正.原文:http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlqu ...

  4. 创建DbContext

    返回总目录<一步一步使用ABP框架搭建正式项目系列教程> 上一篇介绍了<创建实体>,这一篇我们顺其自然地介绍<创建DbContext>. 温故: 提到DbConte ...

  5. EntityFramework中的DbContext使用疑点说明

    1.DbContext怎么在Asp.mvc中使用? public class Repository { //实例化EF容器:有弊端.一个线程里可能会创建多个DbContext //DbContext ...

  6. .NET Core之Entity Framework Core 你如何创建 DbContext

    本文版权归博客园和作者吴双共同所有,欢迎转载,转载和爬虫请注明博客园蜗牛原文地址 http://www.cnblogs.com/tdws/p/5874212.html. 目前国内各大论坛,各位大牛的分 ...

  7. EF和MVC系列文章导航:EF Code First、DbContext、MVC

    对于之前一直使用webForm服务器控件.手写ado.net操作数据库的同学,突然来了EF和MVC,好多新概念泉涌而出,的确犹如当头一棒不知所措.本系列文章可以帮助新手入门并熟练使用EF和MVC,有了 ...

  8. EF DbContext 并发执行时可能出现的问题

    现在许多Web项目都使用了IOC的DI注入组件.其中对象的生命周期管理是非常重要的. 有时我们为了提高请求的响应,经常在请求线程中执行多个子线程,然而忽略了EF的DbContext的生命周期管理. D ...

  9. Entity Framework Code First使用DbContext查询

    DbContext.DbSet及DbQuery是Entity Framework Code First引入的3个新的类,其中DbContext用于保持数据库会话连接,实体变化跟踪及保存,DbSet用于 ...

  10. EF DbContext.Configuration.ProxyCreationEnabled 什么鬼?

    今天在开发项目的时候,使用 EF,突然遇到了这样一个错误: An entity object cannot be referenceed by multiple instances of IEntit ...

随机推荐

  1. 【BZOJ】【1855】【SCOI2010】/【HDOJ】【3401】股票交易

    DP/单调队列优化 题解:http://www.cnblogs.com/jianglangcaijin/p/3799736.html 令f[i][j]表示第 i 天结束后,手里剩下 j 股的最大利润, ...

  2. 使用开关、分段控件和web视图

    #import "XViewController.h" @interface XViewController () @end @implementation XViewContro ...

  3. destoon使用中的一些心得

    //**************************index首页相关参数**************************************// //全局变量 {if $seo_titl ...

  4. AngularJs学习笔记--Guide教程系列文章索引

    在很久很久以前,一位前辈向我推荐AngularJs.但当时我没有好好学习,仅仅是讲文档浏览了一次.后来觉醒了……于是下定决心好好理解这系列的文档,并意译出来(英文水平不足……不能说是翻译,有些实在是看 ...

  5. Difference Between Initialization and Assignment in C++

    Initialization happens when a variable is given a value at the moment it is created. Assignment obli ...

  6. 无法激活服务,因为它不支持 ASP.NET 兼容性

    wcf错误直接上图: 原因: 一般是因为程序添加了启用了AJAX的WCF服务而缺少相关设置出现的错误. 解决方案: 1.webconfig <system.serviceModel> &l ...

  7. 使用Ninject来解决程序中组件的耦合问题

    1.为什么要用Ninject? Ninject是一个IOC容器用来解决程序中组件的耦合问题,它的目的在于做到最少配置.其他的的IOC工具过于依赖配置文件,需要使用assembly-qualified名 ...

  8. java对象群体的组织:Enumeration及Iterator类

    在一般情况下,遍历集合类会使用一下方式: for(int i=0;i<v.size();i++)< p=""> Customer c=(Custormer)v.g ...

  9. 如何理解 MySQL 中的 <=> 操作符?

    问题 : 我在看以前的一个开发者的代码时看到 WHERE p.name <=> NULL 在这个查询语句中 <=>符号是什么意思啊?是不是和 =号是一样啊?还是一个语法错误啊? ...

  10. Linux:chmod -R 777 * 是什么意思?

    首先,chmod命令是linux上用于改变权限的命令,-R 是递归遍历子目录,因为你要操作的文件使用的*通配符.777,第一个7代表文件所属者的权限,第二个7代表文件所属者所在组的权限,第三个7代表其 ...