开发者

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:

Lis开发者_StackOverflow中文版t<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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜