Entity Framework Tutorial Basics(37):Lazy Loading

Lazy Loading:

One of the important functions of Entity Framework is lazy loading. Lazy loading means delaying the loading of related data, until you specifically request for it. For example, Student class contains StudentAddress as a complex property. So, the context first loads all the students from the database, then it will load the address of a particular student when we access StudentAddress property as shown below.

using (var ctx = new SchoolDBEntities())
{
        //Loading students only
        IList<Student> studList = ctx.Students.ToList<Student>();

        Student std = studList[0];

        //Loads Student address for particular Student only (seperate SQL query)
        StudentAddress add = std.StudentAddress;
}

The code shown above will result in two SQL queries. First, it will fetch all students:

SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1]

The, it will send the following query when we get the reference of StudentAddress:

exec sp_executesql N‘SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[Address1] AS [Address1],
[Extent1].[Address2] AS [Address2],
[Extent1].[City] AS [City],
[Extent1].[State] AS [State]
FROM [dbo].[StudentAddress] AS [Extent1]
WHERE [Extent1].[StudentID] = @EntityKeyValue1‘,N‘@EntityKeyValue1 int‘,@EntityKeyValue1=1

However, you can also turn off lazy loading for a particular property or an entire context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false:

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;

public partial class SchoolDBEntities : DbContext
{
    public SchoolDBEntities(): base("name=SchoolDBEntities")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
}

Rules for lazy loading:

  1. context.Configuration.ProxyCreationEnabled should be true.
  2. context.Configuration.LazyLoadingEnabled should be true.
  3. Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not defined as virtual.

Learn how to load entities explicitly in the next section.

时间: 2024-10-23 11:01:25

Entity Framework Tutorial Basics(37):Lazy Loading的相关文章

Entity Framework Tutorial Basics(36):Eager Loading

Eager 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 using the Include() method. In the following example, it gets all the students from the dat

Entity Framework Tutorial Basics(38):Explicit Loading

Explicit Loading with DBContext Even with lazy loading disabled, it is still possible to lazily load related entities, but it must be done with an explicit call. Use the Load method of DBEntityEntry object to accomplish this. The following code expli

Entity Framework Tutorial Basics(1):Introduction

以下系列文章为Entity Framework Turial Basics系列 http://www.entityframeworktutorial.net/EntityFramework5/entity-framework5-introduction.aspx ----------------------------------------------------------------------------------------------------------------------

Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet package and in .NET framework. The .NET framework 4.0/4.5 included EF core API, whereas EntityFramework.dll via NuGet package included EF 5.0 specifi

Entity Framework Tutorial Basics(2):What is Entity Framework?

What is Entity Framework? Writing and managing ADO.Net code for data access is a tedious and monotonous job. Microsoft has provided an O/RM framework called "Entity Framework" to automate database related activities for your application. Microso

Entity Framework Tutorial Basics(3):Entity Framework Architecture

Entity Framework Architecture The following figure shows the overall architecture of the Entity Framework. Let us now look at the components of the architecture individually: EDM (Entity Data Model): EDM consists of three main parts - Conceptual mode

Entity Framework Tutorial Basics(42):Colored Entity

Colored Entity in Entity Framework 5.0 You can change the color of an entity in the designer so that it would be easy to see related groups of entities in the designer from Visual Studio 2012 onwards. To change the color of an entity, select entity i

Entity Framework Tutorial Basics(41):Multiple Diagrams

Multiple Diagrams in Entity Framework 5.0 Visual Studio 2012 provides a facility to split the design time visual representation of the Entity Data Model. This means that you can have multiple diagrams for one Entity Data Model. You can create a new d

Entity Framework Tutorial Basics(34):Table-Valued Function

Table-Valued Function in Entity Framework 5.0 Entity Framework 5.0 supports Table-valued functions of SQL Server. Table-valued functions are similar to stored procedure with one key difference: the result of TVF is composable which means that it can