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. Environment.SpecialFolder.CommonApplicationData

    private void button1_Click(object sender, EventArgs e) { var path=Environment.GetFolderPath(Environm ...

  2. cf div2 236 D

    D. Upgrading Array time limit per test 1 second memory limit per test 256 megabytes input standard i ...

  3. css系列-间隔与间距实例

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. 数据库中已存在名为 'View_Business' 的对象。

    用EF框架+MCF,编译的时候出现:数据库中已存在名为 'View_Business' 的对象. 解决方案: 1.Enable-Migrations2.Add-Migration3.Update-Da ...

  5. http协议本身能获取客户端Mac地址问题

    http 位于网络应用程 应用层 会话层 表示层 传输层 网络层 数据链路层 物理层 数据在最高层开始传输 没经历下面一层加一层的头,然后传入目的电脑再进行一层层的解刨,所以http本来没有mac而接 ...

  6. Combination Sum III

    https://leetcode.com/problems/combination-sum-iii/ Find all possible combinations of k numbers that ...

  7. Integral类型的跨平台使用

    fundamental integral types or extended integral types 我们先通过下图,来了解可以跨平台使用的整数类型: 之所以我们需要以上各种明确指定宽度的int ...

  8. lintcode: 左填充

    题目 实现一个leftpad库,如果不知道什么是leftpad可以看样例 样例 leftpad("foo", 5) >> " foo" leftpa ...

  9. lintcode:移动零

    题目 给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序 注意事项 1.必须在原数组上操作2.最小化操作数   样例 给出 nums = [0, 1, 0, 3, 1 ...

  10. 一个字典通过dictionaryWithDictionary 他们的内存指针是不同的

    一个字典通过dictionaryWithDictionary 他们的内存指针是不同的  来自为知笔记(Wiz)