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. THUPC2017 小 L 的计算题

    求 $k=1,2,\cdots,n \space \space \sum\limits_{i=1}^n a_i^k$ $n \leq 2 \times 10^5$ sol: 时隔多年终于卡过去了 之前 ...

  2. Too Rich(贪心加搜索)

    个人心得:10月份月赛题目,很low,就过了一道水题而且是把所有猜测都提交才过的.这段时间不知道忙什么去了, 也没怎么刷题感觉自己越来越差,还不如新来的大一学弟呢,别人起码天天刷代码到半夜,比起刚在区 ...

  3. LeetCode 361. Bomb Enemy

    原题链接在这里:https://leetcode.com/problems/bomb-enemy/description/ 题目: Given a 2D grid, each cell is eith ...

  4. I would I were a careless child

    I would I were a careless child by George Gordon Byron 1 I would I were a careless child, still dwel ...

  5. C++中rand()函数的用法

    1.rand()不需要参数,它会返回一个从0到最大随机数的任意整数,最大随机数的大小通常是固定的一个大整数. 2.如果你要产生0~99这100个整数中的一个随机整数,可以表达为:int num = r ...

  6. 微信小程序switch组件尺寸控制

    1.修改switch组件的属性值 /* switch */ .wx-switch-input{ width: 82rpx!important; height: 40rpx!important; } / ...

  7. salt-minion dead but pid file exists 正确解决方法

    说明: 看了网上很多关于alt-minion dead but pid file exists 的解决方法,千篇一律的写一个shell脚本 killproc salt-minion 见链接:http: ...

  8. PHP5之前的构造函数与PHP5之后的构造函数的区别

    在PHP5以前的版本中,构造函数的名称必须与类名相同,这种方法在PHP5中仍然可以使用,但现在已经很少有人用了. PHP5以及之后的版本,构造函数用__construct()方法来声明,这样做的好处是 ...

  9. jsp 的url传参中文乱码问题解决办法

    在js文件中,使用连接jsp的url传参,如果参数是中文会出现乱码问题,如下可以解决: 方法一:(已确认 可行) String username = new String(request.getPar ...

  10. HTML 和 CSS

    HTML html是英文hyper text mark-up language(超文本标记语言)的缩写,它是一种制作万维网页面标准语言.   内容摘要   Doctype 告诉浏览器使用什么样的htm ...