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使用疑点说明的更多相关文章

  1. EntityFramework 中支持 BulkInsert 扩展

    本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那 ...

  2. EntityFramework中的线程安全,又是Dictionary

    继上次记一次w3wp占用CPU过高的解决过程(Dictionary和线程安全)后又再次与Dictionary博弈,这一次是在EntityFramework中的Dictionary. 从一个异常说起 这 ...

  3. EntityFramework中支持BulkInsert扩展(转载)

    前言 很显然,你应该不至于使用 EntityFramework 直接插入 10W 数据到数据库中,那可能得用上个几分钟.EntityFramework 最被人诟病的地方就是它的性能,处理大量数据时的效 ...

  4. EntityFramework中支持BulkInsert扩展

    EntityFramework中支持BulkInsert扩展 本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 Ent ...

  5. entityFramework 中decimal精度缺失问题

    在entityFramework中,decimal精度默认为2位数,当要设置的精度大于2位并且数据库中设置的decimal精度大于2位时,则将数据保存在数据库中后两位的小数内容将强制为00 解决方案: ...

  6. EntityFramework中几种操作小结

    目前项目中使用到的EntityFramework中几种操作小结,先标记下.没有详细介绍,后续有空的话再补充一些并完善一下. 列中加入RowVersion时间戳 public class Product ...

  7. 设置EntityFramework中decimal类型数据精度问题(EF默认将只会保留到2为精度)

    原文:设置EntityFramework中decimal类型数据精度 EF中默认的decimal数据精度为两位数,当我们数据库设置的精度大于2时,EF将只会保留到2为精度. e.g. .19990将会 ...

  8. 工作总结 EntityFramework中出现DateTime2异常的完美解决办法

    EntityFramework中出现DateTime2异常的完美解决办法   今天在使用entityframework往数据库插入数据的时候,突然出现了一个数据类型转换异常的问题: System.Da ...

  9. [转]EntityFramework中常用的数据修改方式

    本文转自:http://blog.csdn.net/itmaxin/article/details/47662151 上一篇文章里提到了 EntityFramework中常用的数据删除方式,那么修改对 ...

随机推荐

  1. 【开源】.Net 分布式服务中心

    分布式服务中心 开源地址: http://git.oschina.net/chejiangyi/Dyd.BaseService.ServiceCenter 当垂直应用越来越多,应用之间交互不可避免,将 ...

  2. JavaScript特性(attribute)、属性(property)和样式(style)

    最近在研读一本巨著<JavaScript忍者秘籍>,里面有一篇文章提到了这3个概念. 书中的源码可以在此下载.我将源码放到了线上,如果不想下载,可以直接访问在线网址,修改页面名就能访问到相 ...

  3. 【Linux大系】Linux的概念与体系

    感谢原作者:Vamei 出处:http://www.cnblogs.com/vamei 我在这一系列文章中阐述Linux的基 本概念.Linux操作系统继承自UNIX.一个操作系统是一套控制和使用计算 ...

  4. 【SAP业务模式】之ICS(四):组织单元的配置

    SAP的ICS业务后台配置主要有以下几个配置点: 1.组织单元的配置(公司代码.销售组织.工厂.采购组织等): 2.主数据的部分: 3.订单和开票的定价过程: 4.开票输出类型: 5.公司间发票的配置 ...

  5. 使用gulp解决RequireJS项目前端缓存问题(二)

    1.前言 这一节,我们主要解决在上一节<使用gulp解决RequireJSs项目前端缓存问题(一)>末尾提到的几个问题: 对通过require-config.js引入的js文件修改后,没有 ...

  6. (转) 将ASP.NET Core应用程序部署至生产环境中(CentOS7)

    原文链接: http://www.cnblogs.com/ants/p/5732337.html 阅读目录 环境说明 准备你的ASP.NET Core应用程序 安装CentOS7 安装.NET Cor ...

  7. #26 fibonacci seqs

    Difficulty: Easy Topic: Fibonacci seqs Write a function which returns the first X fibonacci numbers. ...

  8. 面向未来的友好设计:Future Friendly

    一年前翻译了本文的一部分,最近终于翻译完成.虽然此设计思想的提出已经好几年了,但是还是觉得应该在国内推广一下,让大家知道“内容策略”,“移动优先”,“响应式设计”,“原子设计”等设计思想和技术的根源. ...

  9. [httpserver]如何解析HTTP请求报文

    这个http server的实现源代码我放在了我的github上,有兴趣的话可以点击查看哦. 在上一篇文章中,讲述了如何编写一个最简单的server,但该程序只是接受到请求之后马上返回响应,实在不能更 ...

  10. 基于token的多平台身份认证架构设计

    基于token的多平台身份认证架构设计 1   概述 在存在账号体系的信息系统中,对身份的鉴定是非常重要的事情. 随着移动互联网时代到来,客户端的类型越来越多, 逐渐出现了 一个服务器,N个客户端的格 ...