In the book “Entity Framework 4 in Action“, in section 16.1.3 and again in 16.2.4, it is stated
If you have a proxy instance, remember to disable lazy loading before
serializing, or you’ll end up sending unwanted data to the client.
However, the authors never say how to disable lazy loading. In my own searches, I’ve heard of ContextOptions.LazyLoadingEnabled. Is that “the way” this is done? Is there more than one way (besides disabling proxy generation)?
I read in one article that the LazyLoadingEnabled flag only pertains to EntityObject entities, not POCO entites:
Turning lazy loading off will now allow your classes to be serialized
properly. Note, this is if you are using the standard Entity
Framework classes. If you are using POCO, you will have to do
something slightly different.With POCO, the Entity Framework will create proxy classes by default
that allow things like lazy loading to work with POCO. This proxy
basically creates a proxy object that is a full Entity Framework
object that sits between the context and the POCO object. When using
POCO with WCF (or any serialization) just turning off lazy loading
doesn’t cut it. You have to turn off the proxy creation to ensure
that your classes will serialize properly
I suspect the above commentary is simply erroneous.
Yes,
ContextOptions.LazyLoadingEnabledis “the way.” The serialization issue is related, but different. Proxies have a different runtime type. That can mung serialization. The only relation to lazy loading is that pure (non-proxy) POCOs don’t do lazy loading.