DBContext
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的更多相关文章
- EntityFramework Core 1.1是如何创建DbContext实例的呢?
前言 上一篇我们简单讲述了在EF Core1.1中如何进行迁移,本文我们来讲讲EF Core1.1中那些不为人知的事,细抠细节,从我做起. 显式创建DbContext实例 通过带OnConfiguri ...
- Entity Framework 教程——DBContext
DBContext: 在之前的章节<创建实体数据模型>中,EDM为我们创建了SchoolDBEntities 类,它派生子System.Data.Entity.DbContext这个类,这 ...
- [译]DbContext API中使用SqlQuery和ExecuteSqlCommand获取存储过程的输入输出参数
水平有限,欢迎指正.原文:http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlqu ...
- 创建DbContext
返回总目录<一步一步使用ABP框架搭建正式项目系列教程> 上一篇介绍了<创建实体>,这一篇我们顺其自然地介绍<创建DbContext>. 温故: 提到DbConte ...
- EntityFramework中的DbContext使用疑点说明
1.DbContext怎么在Asp.mvc中使用? public class Repository { //实例化EF容器:有弊端.一个线程里可能会创建多个DbContext //DbContext ...
- .NET Core之Entity Framework Core 你如何创建 DbContext
本文版权归博客园和作者吴双共同所有,欢迎转载,转载和爬虫请注明博客园蜗牛原文地址 http://www.cnblogs.com/tdws/p/5874212.html. 目前国内各大论坛,各位大牛的分 ...
- EF和MVC系列文章导航:EF Code First、DbContext、MVC
对于之前一直使用webForm服务器控件.手写ado.net操作数据库的同学,突然来了EF和MVC,好多新概念泉涌而出,的确犹如当头一棒不知所措.本系列文章可以帮助新手入门并熟练使用EF和MVC,有了 ...
- EF DbContext 并发执行时可能出现的问题
现在许多Web项目都使用了IOC的DI注入组件.其中对象的生命周期管理是非常重要的. 有时我们为了提高请求的响应,经常在请求线程中执行多个子线程,然而忽略了EF的DbContext的生命周期管理. D ...
- Entity Framework Code First使用DbContext查询
DbContext.DbSet及DbQuery是Entity Framework Code First引入的3个新的类,其中DbContext用于保持数据库会话连接,实体变化跟踪及保存,DbSet用于 ...
- EF DbContext.Configuration.ProxyCreationEnabled 什么鬼?
今天在开发项目的时候,使用 EF,突然遇到了这样一个错误: An entity object cannot be referenceed by multiple instances of IEntit ...
随机推荐
- 【BZOJ】【2565】最长双回文串
Manacher算法 找出一个最长子串S=X+Y,且X和Y都是回文串,求最长的长度是多少…… 同时找两个串明显很难搞啊……但是我们可以先找到所有的回文串!在找回文串的同时我们可以预处理出来l[i]和r ...
- 引擎设计跟踪(九.14.2h) 开发计划
以后的开发计划: 完善game runtime code, 跑简单的demo目前只有编辑器的运行流程, 没有游戏/demo流程, 图形的测试主要在编辑器上测试, 现在需要测试android系统的图形, ...
- CocoaPods 使用手册
CocoaPods 使用手册 CocoaPods 使用手册 ...
- Kafka的coordinator
(基于0.10版本) Group Management Protocol Kafka的coordiantor要做的事情就是group management,就是要对一个团队(或者叫组)的成员进行管理. ...
- code::blocks 初使用遇到的问题记录
/* 做本程序遇到的问题:由于使用的是CODE::BLOCKS 开发环境,刚开始使用code::blocks是,什么都 没有设置,居然输入的中文字符串,保存项目后,再次打开,code::blocks不 ...
- POJ 1305 Fermat vs. Pythagoras (毕达哥拉斯三元组)
设不定方程:x^2+y^2=z^2若正整数三元组(x,y,z)满足上述方程,则称为毕达哥拉斯三元组.若gcd(x,y,z)=1,则称为本原的毕达哥拉斯三元组. 定理:正整数x,y,z构成一个本原的毕达 ...
- input:text 的value 和 attribute('value') 不是一回事
如题,input:text 当手工输入字符改变其值时,两者就不一样了. 要获得手工输入,不要用attribute('value'), 直接使用value: function getbyid(id){ ...
- DB2对年份的处理Year()
public DataSet GetCustomerAllocListByQC(CustomerAllocQueryDataContract aQC) { StringBuilder sql = ne ...
- lintcode:交错正负数
交错正负数 给出一个含有正整数和负整数的数组,重新排列成一个正负数交错的数组. 注意事项 不需要保持正整数或者负整数原来的顺序. 样例 给出数组[-1, -2, -3, 4, 5, 6],重新排序之后 ...
- Centos环境下部署游戏服务器-常用命令
图1 在Linux的世界,如果你不玩命令,那你见了同行都不好意思和人家打招呼.同时服务器正常状况下放在远端,一般都是开ssh登录服务器,相信远程桌面的人很少见吧.这篇文章说说Linu ...