DBContext:

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.

 namespace EFTutorials
 {
     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 ("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.

数据上下文【 DnContext】【EF基础系列7】的更多相关文章

  1. 【Basics of Entity Framework】【EF基础系列1】

    EF自己包括看视频,看MSDN零零散散的学了一点皮毛,这次打算系统学习一下EF.我将会使用VS2012来学习这个EF基础系列. 现在看看EF的历史吧: EF版本 相关版本特性介绍 EF3.5 基于数据 ...

  2. 10.翻译:EF基础系列---EF中的持久性

    原文链接:http://www.entityframeworktutorial.net/EntityFramework4.3/persistence-in-entity-framework.aspx ...

  3. 1.翻译:EF基础系列--什么是Entity Framework?

    大家好,好久不见,EF系列之前落下了,还是打算重新整理一下. 先说说目前的打算:先简单了解一下EF基础系列-->然后就是EF 6 Code-First系列-->接着就是EF 6 DB-Fi ...

  4. 5.翻译:EF基础系列---EF中的上下文类

    原文地址:http://www.entityframeworktutorial.net/basics/context-class-in-entity-framework.aspx EF中的上下文类是一 ...

  5. 6.翻译:EF基础系列---什么是EF中的实体?

    原文地址:http://www.entityframeworktutorial.net/basics/what-is-entity-in-entityframework.aspx EF中的实体就是继承 ...

  6. 9.翻译:EF基础系列---使用EF开发的方式有哪些?

    原文链接:http://www.entityframeworktutorial.net/choosing-development-approach-with-entity-framework.aspx ...

  7. 4.翻译:EF基础系列--EF架构

    原文地址:http://www.entityframeworktutorial.net/EntityFramework-Architecture.aspx 下面的图形,展示了EF的总体架构: 让我们来 ...

  8. 3.翻译:EF基础系列--EF怎么工作的?

    原文链接:http://www.entityframeworktutorial.net/basics/how-entity-framework-works.aspx 这里,你将会大概了解到EF是怎么工 ...

  9. 8.翻译:EF基础系列----EF中实体的状态

    原文链接:http://www.entityframeworktutorial.net/basics/entity-states.aspx 在实体的生命周期中,EF API维护着每一个实体的状态,对于 ...

  10. 7.翻译:EF基础系列---EF中的实体类型

    原文地址:http://www.entityframeworktutorial.net/Types-of-Entities.aspx 在Entity Framework中有两种实体类型:一种是POCO ...

随机推荐

  1. WebGIS中等值面展示的相关方案简析

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1.背景 等值面是气象.环保等相关项目上常用到的效果展示.在传统的CS项 ...

  2. js学习之函数的参数传递

    我们都知道在 ECMAScript 中,数据类型分为原始类型(又称值类型/基本类型)和引用类型(又称对象类型):这里我将按照这两种类型分别对函数进行传参,看一下到底发生了什么. 参数的理解 首先,我们 ...

  3. Take into Action!

    很久没有认真地写文字了. 刚毕业一两年断断续续在csdn上写过一些当时的工作记录,然后没有坚持下去.有时候是觉得自己不牛,记录的东西旁人看起来也许不值一提:有时候觉得结婚生娃了,然后时间不够用(确实是 ...

  4. MVC还是MVVM?或许VMVC更适合WinForm客户端

    最近开始重构一个稍嫌古老的C/S项目,原先采用的技术栈是『WinForm』+『WCF』+『EF』.相对于现在铺天盖地的B/S架构来说,看上去似乎和Win95一样古老,很多新入行的,可能就没有见过经典的 ...

  5. Hello bokeyuan!

    一个学习技术的年轻人 从2016/09/03进入大学学习计算机科学与技术这门学科,我已经学习了4个月了,大学的生活很枯燥,很麻烦,很多事,与我想象中的大学有很大的区别.但是这都不会影响我想要成为一个技 ...

  6. EMD分析 Matlab 精华总结 附开源工具箱(全)

    前言: 本贴写于2016年12与15日,UK.最近在学习EMD(Empirical Mode Decomposition)和HHT(Hilbert-Huang Transform)多分辨信号处理,FQ ...

  7. Vue.js——60分钟browserify项目模板快速入门

    概述 在之前的一系列vue.js文章,我们都是用传统模式引用vue.js以及其他的js文件的,这在开发时会产生一些问题. 首先,这限定了我们的开发模式是基于页面的,而不是基于组件的,组件的所有代码都直 ...

  8. Spark笔记:复杂RDD的API的理解(下)

    本篇接着谈谈那些稍微复杂的API. 1)   flatMapValues:针对Pair RDD中的每个值应用一个返回迭代器的函数,然后对返回的每个元素都生成一个对应原键的键值对记录 这个方法我最开始接 ...

  9. 「微信小程序」来了

    ps:微信APP Store.微信小程序.微信应用号都是指同一个事情. 苦逼程序猿刚下班到家,还没来得及洗漱,收到条小道消息的推送.于是我有气无力的拿着手机点开了这条推送消息,映入眼帘的就是这张封面图 ...

  10. Android开发学习之路-关于Exception

    Exception在Java中是表示异常的一个类.它是Throwable的子类. 而Exception的子类RuntimeException是一个特殊的异常类,在代码中不需要对此类进行throw,而是 ...