EntityFramework中的DbContext使用疑点说明
1.DbContext怎么在Asp.mvc中使用?
public class Repository
{
//实例化EF容器:有弊端。一个线程里可能会创建多个DbContext
//DbContext db = new DbContext(); //改造:保证一个请求线程中只有一份EF容器(你要明白:一个url请求到服务器,IIS就开一个线程去处理)
protected DbContext GetDbContext
{
get
{
//向线程缓存中查询,如果返回的是null,则创建,同时存入到这个线程缓存中
//注意的是线程缓存CallContext,而不是我们熟悉的HttpRuntime.cache。意味着这个DbContext对象在这个线程内能被其他方法共享。
object efDbContext = CallContext.GetData("DbContext");
if (efDbContext == null)
{
efDbContext = new DbContext();
//存入到这个线程缓存中
CallContext.SetData("DbContext", efDbContext);
}
return efDbContext as DbContext;
}
}
}
这么定义之后,所有需要用到DbContext对象的地方,都调这个方法。
2. 不要随便using或Dispose DbContext会导致延迟加载的不可用,还会有一些其他错误 如IQueryable<T> 下面的方法(.First() /.Count())也不能用。
情况一:
a写法结果正确
PhoneBookEntities phoneBookEntities = new PhoneBookEntities();
var ci = phoneBookEntities.ContactInfo.FirstOrDefault();//这里并没有拿到ci对象里面的GroupInfo属性。
if (ci != null) MessageBox.Show(ci.GroupInfo.GroupName);//是延迟加载,访问 ci.GroupInfo.GroupName 才会去数据库查数据
b写法报错
ContactInfo ci = null;
using (PhoneBookEntities phoneBookEntities = new PhoneBookEntities())
{
ci = phoneBookEntities.ContactInfo.FirstOrDefault();
} if (ci != null) MessageBox.Show(ci.GroupInfo.GroupName);
//报错:此ObjectContext实例已释放,不可再用于需要连接的操作。意味着延迟加载不可用。
情况二:
a写法报错
IQueryable<ContactInfo> ci = null;
using (PhoneBookEntities phoneBookEntities = new PhoneBookEntities())
{
ci = phoneBookEntities.ContactInfo.Where(c => true);
} if (ci != null) MessageBox.Show(ci.Count().ToString());//报错:提示DbContext已经释放。
b写法正确
IQueryable<ContactInfo> ci = null;
using (PhoneBookEntities phoneBookEntities = new PhoneBookEntities())
{
ci = phoneBookEntities.ContactInfo.Where(c => true);
if (ci != null) MessageBox.Show(ci.Count().ToString());//可以返回正确结果。
}
3.为什么你要using 或dispose掉DbContext ?
是担心数据库连接没有释放?还是担心DbContext占用过多资源呢?
首先担心数据库连接没有释放肯定是多余的,因为DbContext在SaveChanges完成后会释放掉打开的数据库连接。
可以反编译一下SaveChages的源码。
担心DbContext占用过多资源也是多余的,有GC回收。
结论,You can call Dispose, but in most common scenarios you don’t need to.
更详细的可以看这个英文博客的文章,其中有 Diego Vega (the Senior SDE Lead on EF) 的回信:
Hello Jon,
The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed. E.g. when you execute a query and iterate over query results using “foreach”, the call to IEnumerable<T>.GetEnumerator() will cause the connection to be opened, and when later there are no more results available, “foreach” will take care of calling Dispose on the enumerator, which will close the connection. In a similar way, a call to DbContext.SaveChanges() will open the connection before sending changes to the database and will close it before returning.
Given this default behavior, in many real-world cases it is harmless to leave the context without disposing it and just rely on garbage collection.
That said, there are two main reason our sample code tends to always use “using” or dispose the context in some other way:
1. The default automatic open/close behavior is relatively easy to override: you can assume control of when the connection is opened and closed by manually opening the connection. Once you start doing this in some part of your code, then forgetting to dipose the context becomes harmful, because you might be leaking open connections.
2. DbContext implements IDiposable following the recommended pattern, which includes exposing a virtual protected Dispose method that derived types can override if for example the need to aggregate other unmanaged resources into the lifetime of the context.
By the way, with DbContext the pattern to open the connection manually and override the automatic open/close behavior is a bit awkward:
((IObjectContextAdapter)dbContext).ObjectContext.Connection.Open()
But we have a bug to make this easier as it used to be with ObjectContext before, e.g.:
dbContext.Database.Connection.Open()
Hope this helps,
Diego
附上参考博客:http://www.cnblogs.com/mecity/archive/2011/07/17/2108508.html
EntityFramework中的DbContext使用疑点说明的更多相关文章
- EntityFramework 中支持 BulkInsert 扩展
本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那 ...
- EntityFramework中的线程安全,又是Dictionary
继上次记一次w3wp占用CPU过高的解决过程(Dictionary和线程安全)后又再次与Dictionary博弈,这一次是在EntityFramework中的Dictionary. 从一个异常说起 这 ...
- EntityFramework中支持BulkInsert扩展(转载)
前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那可能得用上个几分钟.EntityFramework 最被人诟病的地方就是它的性能,处理大量数据时的效 ...
- EntityFramework中支持BulkInsert扩展
EntityFramework中支持BulkInsert扩展 本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 Ent ...
- entityFramework 中decimal精度缺失问题
在entityFramework中,decimal精度默认为2位数,当要设置的精度大于2位并且数据库中设置的decimal精度大于2位时,则将数据保存在数据库中后两位的小数内容将强制为00 解决方案: ...
- EntityFramework中几种操作小结
目前项目中使用到的EntityFramework中几种操作小结,先标记下.没有详细介绍,后续有空的话再补充一些并完善一下. 列中加入RowVersion时间戳 public class Product ...
- 设置EntityFramework中decimal类型数据精度问题(EF默认将只会保留到2为精度)
原文:设置EntityFramework中decimal类型数据精度 EF中默认的decimal数据精度为两位数,当我们数据库设置的精度大于2时,EF将只会保留到2为精度. e.g. .19990将会 ...
- 工作总结 EntityFramework中出现DateTime2异常的完美解决办法
EntityFramework中出现DateTime2异常的完美解决办法 今天在使用entityframework往数据库插入数据的时候,突然出现了一个数据类型转换异常的问题: System.Da ...
- [转]EntityFramework中常用的数据修改方式
本文转自:http://blog.csdn.net/itmaxin/article/details/47662151 上一篇文章里提到了 EntityFramework中常用的数据删除方式,那么修改对 ...
随机推荐
- React使用antd Table生成层级多选组件
一.需求 用户对不同的应用需要有不同的权限,用户一般和角色关联在一起,新建角色的时候会选择该角色对应的应用,然后对应用分配权限.于是写了一种实现的方式.首先应用是一个二级树,一级表示的是应用分组,二级 ...
- 编写高质量代码:改善Java程序的151个建议(第8章:多线程和并发___建议126~128)
建议126:适时选择不同的线程池来实现 Java的线程池实现从根本上来说只有两个:ThreadPoolExecutor类和ScheduledThreadPoolExecutor类,这两个类还是父子关系 ...
- spring boot 实战:我们的第一款开源软件
在信息爆炸时代,如何避免持续性信息过剩,使自己变得专注而不是被纷繁的信息所累?每天会看到各种各样的新闻,各种新潮的技术层出不穷,如何筛选出自己所关心的? 各位看官会想,我们是来看开源软件的,你给我扯什 ...
- C# 程序中嵌入百度地图
本例是对WinForm中使用百度地图的简要介绍.百度地图目前支持Android开发,IOS开发,Web开发,服务接口,具体可以参照'百度地图开放平台'. [动态加载百度地图]涉及到的知识点: WebB ...
- JAVA回调机制解析
一.回调机制概述 回调机制在JAVA代码中一直遇到,但之前不懂其原理,几乎都是绕着走.俗话说做不愿意做的事情叫做突破,故诞生了该文章,算是新年的新气象,新突破! 回调机制是什么?其实回 ...
- Linux设备管理(三)_总线设备的挂接
扒完了字符设备,我们来看看平台总线设备,平台总线是Linux中的一种虚拟总线,我们知道,总线+设备+驱动是Linux驱动模型的三大组件,设计这样的模型就是将驱动代码和设备信息相分离,对于稍微复杂一点的 ...
- 一个无限加载瀑布流jquery实现
实现大概是下面的效果,写了比较详细的注释 <!DOCTYPE html><html> <head> <meta charset="UTF-8&quo ...
- [Xamarin] 透過Native Code呼叫 JavaScript function (转帖)
今天我們來聊聊關於如何使用WebView 中的Javascript 來呼叫 Native Code 的部分 首先,你得先來看看這篇[Xamarin] 使用Webview 來做APP因為這篇文章至少講解 ...
- 一键部署mono 免费空间支持ASP.NET MVC 再也不担心伙食费换空间了
一直以来 部署mono 都是很头疼的事情 因为是我在是不熟悉非win环境,今天偶然发现这个项目,挺好的,分享下 https://github.com/wshearn/openshift-communi ...
- ASP.NET Web API Selfhost宿主环境中管道、路由
ASP.NET Web API Selfhost宿主环境中管道.路由 前言 前面的几个篇幅对Web API中的路由和管道进行了简单的介绍并没有详细的去说明一些什么,然而ASP.NET Web API这 ...