Entity Framework with POCO Serializable Classes and Lazy Loading

I have set up my POCO classes with ICollection for related objects. They are in a WCF Service, so I have decorated them with DataContract/DataMember. I do not use virtual properties for the related objects, because they create a proxy that won't serialize (I get a seemingly unrelated message, "The underlying connection was closed", but when I remove the virtual modifier, that goes away.)

What I am having trouble understanding is how to lazy-load the collections for related objects. I don't think the POCO's can do that for themselves, because they don't have access to the context.

For example, I have a Company class, which has an ICollection<Principals> property. I usually don't want to load all the Principals when I retrieve a Company, but I would like a reference to Company.Principals to go get them. Clearly, Company simply can't do that on its own.

What are folks doing to combine the desires to have (1) POCO objects, (2) typical WCF Serialization, and (3) lazy-loaded related properties?

Answers


Lazy loading requires proxies and virtual navigation properties. If you don't have proxies you must handle loading in different way. For example by using eager loading:

var companies = context.Companies.Include("Principals").ToList();

or with EF 4.1

var companies = context.Companies.Include(c => c.Prinicpals).ToList();

You know which operation should load related principals as well so using eager loading is not a problem. Using lazy loading in WCF service with serialization will always result to load whole object graph.


Need Your Help

Problems with PayPal IPN variables

php paypal paypal-ipn sandbox paypal-sandbox

Im using PayPal as main payment system, so I decided to add it inside my custom built script, however I have problems with IPN variables because when I try to echo any of those variables for exampl...

What are the alternatives to play a youtube video in android within the same activity?

android video android-activity android-intent youtube

So I have got this application where I need to play a youtube video without calling an intent and in the same activity (not using openyoutube :P), what is the appropriate way(s) to do so?