Lazy Loading:
One of the important functions of the Entity Framework is the lazy loading. Lazy loading means delaying the loading of related data, until you specifically request for it. For example, the Student class contains studentaddress as a complex property. So, the context first loads all the students from the database and then it'll load the address of a particular student when We access Studentaddress property as shown below.
using (varnew schooldbentities ()) { //Loading studentsonly IList <Student> studlist = ctx. Students.tolist<student>(); = studlist[0]; // Loads Student address for particular Student only (seperate SQL query) studentaddress add = Std. studentaddress;}
The code shown above would result in the SQL queries. First, it'll fetch all students:
SELECT [Extent1].[StudentID] as [StudentID], [Extent1].[Studentname] as [Studentname], [Extent1].[Standardid] as [Standardid] from [dbo].[Student] as [Extent1]
The It'll 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, does not make it virtual. To turn off-lazy loading for all entities in the context, set it configuration property to false:
usingSystem;usingSystem.Data.Entity;usingSystem.Data.Entity.Infrastructure;usingSystem.Data.Entity.Core.Objects;usingSystem.Linq; Public Partial classschooldbentities:dbcontext{ PublicSchooldbentities ():Base("name=schooldbentities") { This. configuration.lazyloadingenabled =false; } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Throw Newunintentionalcodefirstexception (); }}
Rules for lazy loading:
- context. Configuration.proxycreationenabled should be true.
- context. Configuration.lazyloadingenabled should be true.
- Navigation property should is defined as public, virtual. Context would not does lazy loading if the property was not defined as virtual.
Learn how to load entities explicitly in the next section.
Entity Framework Tutorial Basics (PNS): Lazy Loading