Homam
Homam

Reputation: 23841

How to cache a lazy-loaded property

Background:

I have two tables master and detail. each row in detail contains propertyof master (lazy load).

I want to cache a collection of detail with their masters in a collection like the following:

List<Detail> cachedItems = entities.Details.ToList();

foreach (var d in cachedItems)
    d.master // throws exception 

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

The question:

How can I cache the master object with the detail object without using another collection and I prefer to get them in one round-trip.

Upvotes: 0

Views: 419

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364269

You must explicitly get Master records before you close ObjectContext. If your navigation property in Detail entity is called Master modify your data retrieval query to:

List<Detail> cachedItems = entities.Details.Include("Master").ToList();

Or in case of using Include extension method form EF 4.1

List<Detail> cachedItems = entities.Details.Include(d => d.Master).ToList();

This will load are details with their masters immediately with one round-trip.

Upvotes: 1

Richard Friend
Richard Friend

Reputation: 16018

You could try using the Include function to shape your query results.

Upvotes: 2

Related Questions