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 ...
随机推荐
- 【CoreData】parent-child关系ManagedObjectContext应用
当我们一开始使用CoreData框架和唯一的MOC进行应用的数据持久化的时候,如果创建项目的时候选择了“使用CoreData”,这会是XCode自动生成的模板代码的样子. 同时,配合NSFetched ...
- GS玩家登录
玩家上线 这个过程看了很多很多次了,这里在看下 客户端打开,服务器收到libevent事件,然后new Channel这个过程都付给他各种指针,然后放到channel容器中 .客户端发送c2s_log ...
- 修改MySQL数据库的密码
通过MySQL命令行,可以修改MySQL数据库的密码,下面就为您详细介绍该MySQL命令行,如果您感兴趣的话,不妨一看. 格式:mysql -u用户名 -p旧密码 password 新密码 1.给ro ...
- 吊炸天的 PHP 7 ,你值得拥有
2015年的夏天,虽然来得不算火热,但是在互联网技术的夏天,比任何一年都更为火热. 刚刚才结束了 月底的网易.支付宝.携程以及多家云存储厂商的接连故障的坏消息,6月上旬则迎来了编程语言界两大好消息,第 ...
- EF 中更新模型的问题,这种错误(因为相同类型的其他实体已具有相同的主键值。)
在EF经常在更新模型的时候可能会同时操作一个实体几次. 其实除了SaveChanges外,其它的几次基本都是要查询出一个结果, 例如更新的时候,我们要查一下这个表中有没有相同的纪录之类的. 查询完之后 ...
- (转)8 reviews about de novo genome assembly
转自:http://dskernel.blogspot.com/2012/04/8-reviews-about-de-novo-genome-assembly.html 8 reviews about ...
- hdu 4725
The Shortest Path in Nya Graph Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ...
- SQL技术内幕-4 row_number() over( partition by XX order by XX)的用法(区别于group by 和order by)
partition by关键字是分析性函数的一部分,它和聚合函数不同的地方在于它能返回一个分组中的多条记录,而聚合函数一般只有一条反映统计值的记录,partition by用于给结果集分组,如果没有指 ...
- pycharm控制台中文乱码问题
pycharm控制台中文乱码问题一般是因为之前有配置保存到了文件里, C盘下.pycharm文件夹下有配置文件,删除文件后重装pycharm,配置会重置 不过最后解决问题的做法是删除配置文件后,重新装 ...
- Hortworks Hadoop生态圈简介
Hortworks 作为Apache Hadoop2.0社区的开拓者,构建了一套自己的Hadoop生态圈,包括存储数据的HDFS,资源管理框架YARN,计算模型MAPREDUCE.TEZ等,服务于数据 ...