数据上下文【 DnContext】【EF基础系列7】
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】的更多相关文章
- 【Basics of Entity Framework】【EF基础系列1】
EF自己包括看视频,看MSDN零零散散的学了一点皮毛,这次打算系统学习一下EF.我将会使用VS2012来学习这个EF基础系列. 现在看看EF的历史吧: EF版本 相关版本特性介绍 EF3.5 基于数据 ...
- 10.翻译:EF基础系列---EF中的持久性
原文链接:http://www.entityframeworktutorial.net/EntityFramework4.3/persistence-in-entity-framework.aspx ...
- 1.翻译:EF基础系列--什么是Entity Framework?
大家好,好久不见,EF系列之前落下了,还是打算重新整理一下. 先说说目前的打算:先简单了解一下EF基础系列-->然后就是EF 6 Code-First系列-->接着就是EF 6 DB-Fi ...
- 5.翻译:EF基础系列---EF中的上下文类
原文地址:http://www.entityframeworktutorial.net/basics/context-class-in-entity-framework.aspx EF中的上下文类是一 ...
- 6.翻译:EF基础系列---什么是EF中的实体?
原文地址:http://www.entityframeworktutorial.net/basics/what-is-entity-in-entityframework.aspx EF中的实体就是继承 ...
- 9.翻译:EF基础系列---使用EF开发的方式有哪些?
原文链接:http://www.entityframeworktutorial.net/choosing-development-approach-with-entity-framework.aspx ...
- 4.翻译:EF基础系列--EF架构
原文地址:http://www.entityframeworktutorial.net/EntityFramework-Architecture.aspx 下面的图形,展示了EF的总体架构: 让我们来 ...
- 3.翻译:EF基础系列--EF怎么工作的?
原文链接:http://www.entityframeworktutorial.net/basics/how-entity-framework-works.aspx 这里,你将会大概了解到EF是怎么工 ...
- 8.翻译:EF基础系列----EF中实体的状态
原文链接:http://www.entityframeworktutorial.net/basics/entity-states.aspx 在实体的生命周期中,EF API维护着每一个实体的状态,对于 ...
- 7.翻译:EF基础系列---EF中的实体类型
原文地址:http://www.entityframeworktutorial.net/Types-of-Entities.aspx 在Entity Framework中有两种实体类型:一种是POCO ...
随机推荐
- 【SAP业务模式】之ICS(五):定价配置
本篇博文讲述ICS业务中的定价配置. 1.定义销售订单类型 目录:SPRO-销售与分销-销售-销售凭证-销售凭证抬头-定义销售凭证类型 事务代码:VOV8 2.定义销售订单类型 目录:SPRO-销售与 ...
- Android 在Android代码中执行命令行
1.路径最好不要是自己拼写的路径/mnt/shell/emulated/0/wifidog.conf 最好是通过方法获取的路径,不然可能导致命令无效 (挂载点的原因) public static f ...
- 关于Genymotion下载比较慢的解决办法
Genymotion号称Android模拟器中运行最快的,但是服务器在国外,Android镜像下载起来那个速度就不想说了. Add new device后下载速度太慢了,容易失败 先登录,然后add, ...
- Linux初识
在这篇文章中你讲看到如下内容: 计算机的组成及功能: Linux发行版之间的区别和联系: Linux发行版的基础目录及功用规定: Linux系统设计的哲学思想: Linux系统上获取命令帮助,及man ...
- [原创]Macbook Pro Retina 15吋安装Windows 7和Windows 8.1方法
前言 本以为有Bootcamp神器在手,Macbook装Win系统应该是不在话下,没想到着实折腾了一番.期间因为误操作导致OSX也挂掉进不去只得磁盘全部抹掉网络恢复安装.为了让大家少走弯路,提供个人安 ...
- 机器指令翻译成 JavaScript —— No.3 流程分割
上一篇 我们讨论了跳转指令,并实现「正跳转」的翻译,但最终困在「负跳转」上.而且,由于线程模型的差异,我们不能 1:1 的翻译,必须对流程进行一些改造. 当初之所以选择翻译,而不是模拟,就是出于性能考 ...
- windows phone如何才能在中国翻身?
最近的新闻告诉我们,Android和IOS的系统继续保持市场领先,并且Android的市场份额达到了历史最高点. 做为windows phone的消费者,作为微软粉丝,我感到十分的不爽. 前几天MIU ...
- Glide源码导读
最近比较无聊,为了找点事干,就花了两天时间把Glide的源码大概看了一下.刚开始看Glide的源码头脑还是比较乱的,因为作者引入了几个概念,又大量用了泛型,如果不了解这些概念读起代码来就比较痛苦,我也 ...
- 安装keil MDK5
昨天买的stm32板子今天就到了,顺丰速度确实很快. 我这是刚开始整STM32,首先需要下载keil MDK,直接杀去keil官网下载,其实对于学习者,我建议大家下载软件能去官网就去官网,尽量少用二道 ...
- 使用topshelf包装redis为windows服务
Redis服务端目前用的是控制台程序运行,部署的时候能作为windows服务后台运行感觉更好.找到一篇文章Running Redis as a Windows Service,利用win ...