Data Developer Center > Learn > Entity Framework > Get Started > Loading Related Entities

Loading Related Entities

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.

The following topics are covered on this page:

Eagerly Loading

Eager loading is the process whereby a query for one type of entity also loads related entities as part of the query. Eager loading is achieved by use of the Include method. For example, the queries below will load blogs and all the posts related to each blog.

using (var context = new BloggingContext()) 
{
    // Load all blogs and related posts
    var blogs1 = context.Blogs
                          .Include(b => b.Posts)
                          .ToList();
 
    // Load one blogs and its related posts
    var blog1 = context.Blogs
                        .Where(b => b.Name == "ADO.NET Blog")
                        .Include(b => b.Posts)
                        .FirstOrDefault();
 
    // Load all blogs and related posts 
    // using a string to specify the relationship
    var blogs2 = context.Blogs
                          .Include("Posts")
                          .ToList();
 
    // Load one blog and its related posts 
    // using a string to specify the relationship
    var blog2 = context.Blogs
                        .Where(b => b.Name == "ADO.NET Blog")
                        .Include("Posts")
                        .FirstOrDefault();
}

Note that Include is an extension method in the System.Data.Entity namespace so make sure you are using that namespace.

Eagerly loading multiple levels

It is also possible to eagerly load multiple levels of related entities. The queries below show examples of how to do this for both collection and reference navigation properties.

using (var context = new BloggingContext()) 
{
    // Load all blogs, all related posts, and all related comments
    var blogs1 = context.Blogs
                       .Include(b => b.Posts.Select(p => p.Comments))
                       .ToList();
 
    // Load all users their related profiles, and related avatar
    var users1 = context.Users
                        .Include(u => u.Profile.Avatar)
                        .ToList();
 
    // Load all blogs, all related posts, and all related comments 
    // using a string to specify the relationships
    var blogs2 = context.Blogs
                       .Include("Posts.Comments")
                       .ToList();
 
    // Load all users their related profiles, and related avatar 
    // using a string to specify the relationships
    var users2 = context.Users
                        .Include("Profile.Avatar")
                        .ToList();
}

Note that it is not currently possible to filter which related entities are loaded. Include will always being in all related entities.

Lazy Loading

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. When using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook. For example, when using the Blog entity class defined below, the related Posts will be loaded the first time the Posts navigation property is accessed:

public class Blog 

    public int BlogId { get; set; } 
    public string Name { get; set; } 
    public string Url { get; set; } 
    public string Tags { get; set; } 
 
    public virtual ICollection<Post> Posts { get; set; } 
}

Turn lazy loading off for serialization

Lazy loading and serialization don’t mix well, and if you aren’t careful you can end up querying for your entire database just because lazy loading is enabled. Most serializers work by accessing each property on an instance of a type. Property access triggers lazy loading, so more entities get serialized. On those entities properties are accessed, and even more entities are loaded. It’s a good practice to turn lazy loading off before you serialize an entity. The following sections show how to do this.

Turning off lazy loading for specific navigation properties

Lazy loading of the Posts collection can be turned off by making the Posts property non-virtual:

public class Blog 

    public int BlogId { get; set; } 
    public string Name { get; set; } 
    public string Url { get; set; } 
    public string Tags { get; set; } 
 
    public ICollection<Post> Posts { get; set; } 
}

Loading of the Posts collection can still be achieved using eager loading (see Eagerly loading related entities above) or the Load method (see Explicitly loading related entities below).

Turn off lazy loading for all entities

Lazy loading can be turned off for all entities in the context by setting a flag on the Configuration property. For example:

public class BloggingContext : DbContext 
{
    public BloggingContext()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }
}

Loading of related entities can still be achieved using eager loading (see Eagerly loading related entities above) or the Load method (see Explicitly loading related entities below).

Explicitly Loading

Even with lazy loading disabled it is still possible to lazily load related entities, but it must be done with an explicit call. To do so you use the Load method on the related entity’s entry. For example:

using (var context = new BloggingContext()) 
{
    var post = context.Posts.Find(2);
 
    // Load the blog related to a given post
    context.Entry(post).Reference(p => p.Blog).Load();
 
    // Load the blog related to a given post using a string 
    context.Entry(post).Reference("Blog").Load();
 
    var blog = context.Blogs.Find(1);
 
    // Load the posts related to a given blog
    context.Entry(blog).Collection(p => p.Posts).Load();
 
    // Load the posts related to a given blog 
    // using a string to specify the relationship
    context.Entry(blog).Collection("Posts").Load();
}

Note that the Reference method should be used when an entity has a navigation property to another single entity. On the other hand, the Collection method should be used when an entity has a navigation property to a collection of other entities.

Applying filters when explicitly loading related entities

The Query method provides access to the underlying query that the Entity Framework will use when loading related entities. You can then use LINQ to apply filters to the query before executing it with a call to a LINQ extension method such as ToList, Load, etc. The Query method can be used with both reference and collection navigation properties but is most useful for collections where it can be used to load only part of the collection. For example:

using (var context = new BloggingContext()) 
{
    var blog = context.Blogs.Find(1);
 
    // Load the posts with the 'entity-framework' tag related to a given blog
    context.Entry(blog)
        .Collection(b => b.Posts)
        .Query()
        .Where(p => p.Tags.Contains("entity-framework")
        .Load();
 
    // Load the posts with the 'entity-framework' tag related to a given blog 
    // using a string to specify the relationship 
    context.Entry(blog)
        .Collection("Posts")
        .Query()
        .Where(p => p.Tags.Contains("entity-framework")
        .Load();
}

When using the Query method it is usually best to turn off lazy loading for the navigation property. This is because otherwise the entire collection may get loaded automatically by the lazy loading mechanism either before or after the filtered query has been executed.

Note that while the relationship can be specified as a string instead of a lambda expression, the returned IQueryable is not generic when a string is used and so the Cast method is usually needed before anything useful can be done with it.

Using Query to count related entities without loading them

Sometimes it is useful to know how many entities are related to another entity in the database without actually incurring the cost of loading all those entities. The Query method with the LINQ Count method can be used to do this. For example:

using (var context = new BloggingContext()) 
{
    var blog = context.Blogs.Find(1);
 
    // Count how many posts the blog has 
    var postCount = context.Entry(blog)
                          .Collection(b => b.Posts)
                          .Query()
                          .Count();
}

Data Developer Center > Learn > Entity Framework > Get Started > Loading Related Entities的更多相关文章

  1. Entity Framework Tutorial Basics(33):Spatial Data type support in Entity Framework 5.0

    Spatial Data type support in Entity Framework 5.0 MS SQL Server 2008 introduced two spatial data typ ...

  2. Entity Framework应用:Loading Entities

    Entity Framework允许控制对象之间的关系,在使用EF的过程中,很多时候我们会进行查询的操作,当我们进行查询的时候,哪些数据会被加载到内存中呢?所有的数据都需要吗?在一些场合可能有意义,例 ...

  3. EntityFramework 学习 一 Spatial Data type support in Entity Framework 5.0

    MS SQl Server引进两种特殊的数据类型geography and geometry public partial class Course { public Course() { this. ...

  4. Entity Framework 6 执行Linq to Entities异常"p__linq__1 : String truncation: max=0, len=2, value='测试'"

    场景再现 我需要查询公司名称包含给定字符串的公司,于是我写了下面的测试小例子: var condition = "测试"; var query = from b in db.Com ...

  5. Entity Framework Tutorial Basics(36):Eager Loading

    Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...

  6. Lerning Entity Framework 6 ------ Inserting, Querying, Updating, and Deleting Data

    Creating Entities First of all, Let's create some entities to have a test. Create a project Add foll ...

  7. [转]Entity Framework and SQL Azure

    本文转自:https://msdn.microsoft.com/zh-cn/library/gg190738 Julie Lerman http://thedatafarm.com April 201 ...

  8. EF是啥?【What is Entity Framework?】(EF基础系列2)

    EF产生的背景: 编写ADO.NET访问数据的代码,是沉闷而枯燥的,所以微软提供了一个对象关系映射框架(我们称之为EF),通过EF可以自动帮助我们的程序自动生成相关数据库. Writing and m ...

  9. What is Entity Framework?

    1.什么是EntityFramework? http://www.entityframeworktutorial.net/what-is-entityframework.aspx Writing an ...

随机推荐

  1. Redis 2:简单使用

    导读:上一篇博客对于Redis进行了简单的介绍,本篇博客就浅显的说一下Redis的基本操作使用.本次测试的环境是window8.1,呃,没用Linux等其他系统,就下载的window环境的安装包. 一 ...

  2. cordova 日曆 聯系人 插件使用

    日曆插件 聯係人插件 我用聯係人插件, function onSuccess(contact) { alert("Save Success"); }; function onErr ...

  3. 电脑U盘启动总结

    1:联想G410(笔记本) FN+F2:进入BIOS,FN+F12,快速启动选择. boot mode—>Legacy support,boot priority—>Legacy firs ...

  4. CICS的database中R D中参数的含义

    见链接 http://blog.163.com/ajj_star/blog/static/1626772542010328113513429/ Region Definitions (RD) 定义了所 ...

  5. 设计模式-工厂方法模式(FactoryMethod)

    简介: 简单工厂模式将类的示例化放在工厂对象中. 工厂方法模式是简单工厂模式的延伸,不同的是其将子类的实例化延迟到子类工厂中实现,本身仅定义一个创建对象的接口. 工厂方法模式主要由四部分组成: 1.抽 ...

  6. iConvert Icons 图标转换生成利器,支持Windows, Mac OS X, Linux, iOS,和Android等系统

    这是一款在线图标转换工具,生成的图标支持Windows, Mac OS X, Linux, iOS, 和 Android等主流系统. 可以上传图标文件转化成另一个平台下的图标文件,例如将windows ...

  7. CentOS学习笔记--基本命令--文件与目录管理

    Linux基本命令--文件与目录管理 本节节选自鸟哥的 Linux 私房菜 -- 基础学习篇目录  第七章.Linux 文件与目录管理  ls(文件与目录的检视) ls命令就是list的缩写,ls可以 ...

  8. 两个和尚抬水有水喝,三个和尚抬水没水喝------IT项目管理之组织架构

    说到项目经理岗位,一般的想法是,一个项目只能有一个项目经理,否则责任不明,互相推诿.偏偏IT项目需要有两个甚至三个项目经理.原因何在呢? 典型的IT项目(不包含纯技术或工具类项目)是把用户的需求转化成 ...

  9. Log4net使用笔记

    Log4net使用笔记   编写人:CC阿爸 2013-10-29 近来在处理项目时候,想将系统的操作日志以文本的形式记录下来,方便对系统操作记录进行追踪. 经过在网上搜索部分解决方案,大致可以归纳如 ...

  10. Java通过Executors提供四种线程池

    http://cuisuqiang.iteye.com/blog/2019372 Java通过Executors提供四种线程池,分别为:newCachedThreadPool创建一个可缓存线程池,如果 ...