Home > C#, Entity Framework > Entity Framework, LazyLoading & WCF

Entity Framework, LazyLoading & WCF


Entity Framework and WCF work well together in providing a good back end service layer for a range of application types. One gotcha however that can easily catch you out without being very visible is LazyLoading.

LazyLoading defers the loading of related entities, e.g. Order for Customers, until they are accessed via a navigation property.

In the Entity Framework runtime, the default value of the LazyLoadingEnabled property in an instance of an ObjectContext is false. However, if you use the Entity Framework tools to create a new model and the corresponding generated classes, LazyLoadingEnabled is set to true in the object context’s constructor.

Thus it is possible for LazyLoading to be enabled without really explicitly requesting the feature.

There is no problem with this and LazyLoading is a great feature if you are not using WCF, however the serialisation of objects to XML before being sent over the wire causes all the navigation properties to be accessed throughout the model and thus it is very easy to accidentally serialise the whole object graph which consequently has the effect of slowing down the data access via WCF.

LazyLoading can be switched of explicitly in the ObjectContext using the code below or for Entity Framework as a whole by changing the properties of the EDMX.

public void QueryWithoutLazyLoading()
{
    using (AdventureWorksEntities context = new AdventureWorksEntities())
    {
        context.ContextOptions.LazyLoadingEnabled = false;
        ...
    }
}

Listing 1 – Disabling LazyLoading on the ObjectContext
In the next post I’ll look at how to work around not using LazyLoading with WCF as well as how to build up queries in manageable chunks that can be specialised based on logic.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: