推荐文章html
EF性能之关联加载 总结很好数据库
一:介绍三种加载方式框架
Entity Framework做为一个优秀的ORM框架,它使得操做数据库就像操做内存中的数据同样,可是这种抽象是有性能代价的,故鱼和熊掌不能兼得。可是,经过对EF的学习,能够避免没必要要的性能损失。本篇只介绍关联实体的加载的相关知识,这在我以前的文章中都有介绍。
咱们已经了解到EF的关联实体加载有三种方式:Lazy Loading,Eager Loading,Explicit Loading,其中Lazy Loading和Explicit Loading都是延迟加载。
(一)Lazy Loading使用的是动态代理,默认状况下,若是POCO类知足如下两个条件,EF就使用Lazy Loading:
POCO类是Public且不为Sealed。
导航属性标记为Virtual。
关闭Lazy Loading,能够将LazyLoadingEnabled设为false,若是导航属性没有标记为virtual,Lazy Loading也是不起做用的。
(二)Eager Loading使用Include方法关联预先加载的实体。
(三)Explicit Loading使用Entry方法,对于集合使用Collection,单个实体则使用Reference。
2-1:Lazy Loading模式ide
做用性能
/*在读取父类的时候自动将全部关联类的实体都加载出来 **好比 */ public class Site { [Key] public int Id{ get; set; } public string Name { get; set; } /*virtual 知识点关键字:EF三种关联加载 Lazy Loading,Eager Loading,Explicit Loading*/ public virtual ICollection<News> Newss { get; set; } } /*经过db.Site.FirstOrDefault();会加载出一个符合条件的Site实体,而且Site实体下的全部News对象也都**加载出来而且保存在Newss中 */
使用方法学习
两步 第一:在须要延迟加载的属性前加上virtual ,该属性的类型能够是任务的集合类型ICOLLOCT<T>或者是0/1..1关联属性。 如: public virtual List<Product> Products { get; set; } 第二:在context构造器中开启延迟加载功能 Configuration.LazyLoadingEnabled = true; //EF6 以前的版本多是ContextOptions.LazyLoadingEnabled = true;
涨姿式spa
//既支持在Content构造器中一次设置,程序所有通用 //也能够在程序执行查询等命令以前动态设置 //好比 using (var db = new SpriderContent()) { db.Configuration.LazyLoadingEnabled = false OrgPlate plate = db.OrgPlates.FirstOrDefault(); }
2-2:Eager Loading模式代理
做用:code
EF不会再帮你把关联实体加载出来,而只会把当前表的内容读取出来,提升效率
使用方法:htm
//同Lazy Loading恰好相反 dConfiguration.LazyLoadingEnabled = false private static void EagerLoading(EFLoadingContext ctx) { //发送一条查询到数据库库,查询全部的province并关联city和governor var list = ctx.Provines.Include(t => t.Cities).Include(t => t.Governor); foreach (var province in list) { //无论ctx.Configuration.LazyLoadingEnabled为false,仍是没有标注导航属性virtual,都不会抛出异常 Print(province); } } //例子来源于http://www.cnblogs.com/nianming/p/3494781.html
2-3:Explicit Loading模式
使用方法
1:Configuration.LazyLoadingEnabled = false; 2:Explicit Loading使用Entry方法,对于集合使用Collection,单个实体则使用Reference。 void ExplicitLoading(EFLoadingContext ctx) { //发送一条查询到数据库,查询全部的province var list = ctx.Provines.ToList(); foreach (var province in list) { var p = ctx.Entry(province); //发送一条查询,查询全部当前province的city p.Collection(t => t.Cities).Load(); //发送一条查询,查询当前province的governor p.Reference(t => t.Governor).Load(); //无论ctx.Configuration.LazyLoadingEnabled为false,仍是没有标注导航属性virtual,都不会抛出异常 Print(province); } } //例子引用自http://www.cnblogs.com/nianming/p/3494781.html