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 ...
随机推荐
- 服务器NPC的ID如何分配的
服务器ID分配包括NPC,Monster,Pet的ID分配都是调用allocateUID然后自动保存的ID加一,pet说是通过玩家的ID移位获得的,调试一下发现还是调用allocateUID,如果通过 ...
- topcoder 643 DIV2
太弱了,太弱了! A:基本的判断吧,然后就是边界问题,写了好久,结果发现时房间第二个交的.. B:真心跪了,还好想出来了,思路想的太慢太慢,结果交上去,落后太多,不过HACK时很多人挂了, 这也是DI ...
- jQuery提升性能技巧及个人总结
1.将jquery对象缓存起来在for循环中,不要每次都要访问数组的length属性,我们应该先将对象缓存进一个变量然后再操作,如下所示: 代码如下:var myLength = myArray.le ...
- HDU2295 Radar (DLX)
下面的代码99%参考了这个网站http://www.cnblogs.com/183zyz/archive/2011/08/07/2130193.html 人生的第一道DLX肯定是需要作一些参考的啦. ...
- ***mysql中查询今天、昨天、上个月sql语句
今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天Select * FROM 表名 Where TO_DAYS( NOW( ) ...
- POJ 1027 The Same Game(模拟)
题目链接 题意 : 一个10×15的格子,有三种颜色的球,颜色相同且在同一片内的球叫做cluster(具体解释就是,两个球颜色相同且一个球可以通过上下左右到达另一个球,则这两个球属于同一个cluste ...
- 关于在linux下清屏的几种技巧
在windows的DOS操作界面里面,清屏的命令是cls,那么在linux 里面的清屏命令是什么呢?下面笔者分享几种在linux下用过的清屏方法. 1.clear命令.这个命令将会刷新屏幕,本质上只是 ...
- 浅谈Asp.net的sessionState
见:http://my.oschina.net/kavensu/blog/330436
- sql 数据库换行
制表符 CHAR(9) 换行符 CHAR(10) 回车 CHAR(13)
- hdu 3590 PP and QQ
知识储备: Anti-SG 游戏和 SJ 定理 [定义](anti-nim 游戏) 桌子上有 N 堆石子,游戏者轮流取石子. 每次只能从一堆中取出任意数目的石子,但不能不取. 取走最后一 ...