Entity Framework中的几种加载方式

        在Entity Framework中有三种加载的方式,分别是延迟加载,自动加载和显示加载。下面用一个例子来讲明:如今有两个表,一个是资料表(Reference),另一个表是资料分类表(Catalog)。一个资料属于某一个分类,可是一个分类下能够包含多个资料。是一个一对多的关系。html

       两个实体类代码以下:app

public partial class Catalog
{
    public Catalog()
    {
        this.References = new List<Reference>();
    }
 
    public string CatalogID { get; set; }
    public string CatalogName { get; set; }
    public ICollection<Reference> References { get; set; }
}
public partial class Reference
{
    public string ReferenceID { get; set; }
    public string CatalogID { get; set; }
    public string ReferenceName { get; set; }
    public virtual Catalog Catalog { get; set; }
}

        一、延迟加载。(若是要使用延迟加载,一是Context中的 this.Configuration.LazyLoadingEnabled =true;另外是要求导航属性前面有virtual关键字,任何条件缺一不可);this

List<Reference> refeList = new List<Reference>();//此时只加载了Reference
 
refeList = dbContext.Set<Reference>().ToList();
 
Catalog c = refeList[0].Catalog;//此时会自动生成一条Sql语句,查询这个Referece里面的Catalog,即实现了延迟加载

        二、手动加载,手动加载是在我须要的时候,经过调用Include方法来实现加载的。手动加载不须要任何条件。spa

return dbContext.Set<Reference>().Include("Catalog").ToList();
 
//能够直接传入字段的名称,也能够经过lamaba来传递,可是使用后一种方法的时候,须要添加using System.Data.Entity;引用
//return dbContext.Set<Reference>().Include(t => t.Catalog).ToList();

       手动加载时,是一次性的加载,只生成一条Sql语句,这条Sql语句是同时查询Reference以及Reference中对应的Catalog 。若是是一对多的关系,有的时候,根本不须要延迟加载,因此通常都把延迟加载关闭掉,在须要使用的时候,经过Include来手动的加载;Include通常适用于一对多的关系时,当读取多的时候,能够手动把一的那个实体加载上。好比读取一个资料时,把这个资料对应的分类实体也读取出来。可是反过来,通常就不用,通常不多会在读取分类时,就把这个分类下的全部资料读取出来,除非是查询的时候。code

        三、显式的加载,当咱们想在使用的时候,显式的调用去加载,那么咱们可使用Entry中的Collection(List)或者Reference(单个实体)去加载;当咱们在读取一个分类的时候,咱们能够显示的去加载,每一个分类里面的资料。如:htm

using (DbContext dbContext = new TestDatabaseContext())
{
    entityList = dbContext.Set<Catalog>().OrderBy(t=>t.CatalogID).Skip(1).Take(3).ToList();
 
    foreach (Catalog c in entityList)
    {
        dbContext.Entry(c).Collection(t => t.References).Load();//显式加载
    }
 
    return entityList;
}

 

参考资料:blog

http://www.cnblogs.com/nianming/p/3494781.html#2861128ip

http://www.cnblogs.com/nianming/archive/2013/01/09/2846952.htmlget

相关文章
相关标签/搜索