Serializing Entity Framework Objects for Azure Cache

we use Azure Caching directly (and not through one of the available Entity Framework shells). Apparently, for distributed caching, we need to serialize objects. Unfortunately, this causes problems with lazy DbContext-based downloads used for navigation properties.

I see we can use a custom serializer to map proxies to empty collections (if they are not loaded) or ordinary objects (if they are loaded), but I'm not sure about the implementation. One possible implementation may be based on the one used by WCF , but I'm not sure that Azure works the same.

The ideal solution (and why I point to ProxyDataContractResolver) would be where where the serialization happens:

  • If the navigation property is already loaded, the data will be serialized as if it were a regular collection,
  • and if they are not loaded, they will not be serialized (I would like the lazy loading to return after deserialization for the latter case, but this is acceptable if it is not).

Has anyone manually fixed this issue in an elegant way?

Thanks in advance!

+4
source share
2 answers

I assume that if you want to cache EF objects, you do not need to lazily load or track changes for these objects.

I believe that both of these functions are enabled through proxy objects, which will cause serialization problems (since you do not want to serialize the proxy server).

If you disable the DbContext.Configuration.ProxyCreationEnabled property, then serializing the actual object, not the proxy server, should work fine. This is usually required when returning POCO objects on top of WCF, but the same for other serialization scripts such as this.

+2
source

If you detach the EF object from the DbContext before it is serialized, this disables lazy loading, so your custom serializer will not try to serialize anything that is not yet part of the entity graph.

Then, when you return from the cache, if you attach it to a new (identical) DbContext, which should reuse lazy loading.

(Caution: after disconnecting an object from the context, any new requests containing the same object will create a new, attached copy, so you will need to be careful to encode different versions of the same object to avoid problems with several potentially dangerous objects, but it means that you should do what you want.

+1
source

All Articles