DBContext:

As you have seen in the previous Create Entity Data Model section, EDM generates the SchoolDBEntities class, which was derived from the System.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.

Entity Framework Tutorial Basics(7):DBContext的更多相关文章

  1. Entity Framework Tutorial Basics(1):Introduction

    以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/enti ...

  2. Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

    Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...

  3. Entity Framework Tutorial Basics(43):Download Sample Project

    Download Sample Project: Download sample project for basic Entity Framework tutorials. Sample projec ...

  4. Entity Framework Tutorial Basics(42):Colored Entity

    Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that ...

  5. Entity Framework Tutorial Basics(41):Multiple Diagrams

    Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design ...

  6. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

  7. Entity Framework Tutorial Basics(36):Eager Loading

    Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...

  8. Entity Framework Tutorial Basics(34):Table-Valued Function

    Table-Valued Function in Entity Framework 5.0 Entity Framework 5.0 supports Table-valued functions o ...

  9. Entity Framework Tutorial Basics(33):Spatial Data type support in Entity Framework 5.0

    Spatial Data type support in Entity Framework 5.0 MS SQL Server 2008 introduced two spatial data typ ...

随机推荐

  1. 修改分区后的 Grub rescue

    声明:这里用到的知识不是原创,综合了几篇教程的成果.找的时候比较混乱,所以来源已经不确定.希望原作者见谅. 系统是Windows 8.1 和 Ubuntu 14.04, Windows是先装的, gr ...

  2. 洛谷【P1616】疯狂的采药

    浅谈\(DP\):https://www.cnblogs.com/AKMer/p/10437525.html 题目传送门:https://www.luogu.org/problemnew/show/P ...

  3. BZOJ4520:[CQOI2016]K远点对

    浅谈\(K-D\) \(Tree\):https://www.cnblogs.com/AKMer/p/10387266.html 题目传送门:https://lydsy.com/JudgeOnline ...

  4. Common 通用类库

    /// <summary> /// 传入虚拟路径 返回全路径的html字符串 /// </summary> /// <param name="context&q ...

  5. df 命令-显示目前磁盘剩余的磁盘空间

    linux中df命令的功能是用来检查linux服务器的文件系统的磁盘空间占用情况.可以利用该命令来获取硬盘被占用了多少空间,目前还剩下多少空间等信息. 1.命令格式: df [选项] [文件] 2.命 ...

  6. 转:InnoDB多版本(MVCC)实现简要分析

    InnoDB多版本(MVCC)实现简要分析 基本知识 假设对于多版本(MVCC)的基础知识,有所了解.InnoDB为了实现多版本的一致读,采用的是基于回滚段的协议. 行结构 InnoDB表数据的组织方 ...

  7. 侯捷STL学习(八)-- 深度探索deque

    layout: post title: 侯捷STL学习(八) date: 2017-07-19 tag: 侯捷STL --- 第十八节 深度探索deque上 duque内存结构 分段连续,用户看起来是 ...

  8. DripRoad(点滴之路)

    关于DripRoad DripRoad 意为点滴之路,程序员之路在于点滴积累!是的,这些积累包括技术能力,沟通能力,业务能力等等.   我 我是唐志伟,2009年一个人来上海,就读于上海医疗器械高等专 ...

  9. Python中str.format()字典及list传入详解

  10. 部署和调优 1.9 samba 部署和优化-3

    实践2 要求:共享一个目录,使用用户名和密码登录后才可以访问,要求可以读写 打开配置文件 vim /etc/samba/smb.conf 改为security = user 在最后面增加一段 [den ...