Question

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

I see we can use a custom serializer in order to map proxies to empty collections (if not loaded) or to normal objects (if loaded), but I am not sure about the implementation. One possible implementation can be based on the one used by WCF, but I am not sure Azure works the same way.

The ideal solution (and that's why I point to ProxyDataContractResolver) would be one where, when serialization happens:

  • IF the navigation property has been already loaded the data would be serialized as if it were a normal Collection,
  • and if they are not loaded, they won't be serialized (I would like lazy loading to work back after deserialization for the latter case, but it's acceptable if it doesn't).

Has anyone manually fixed that problem in an elegant way?

Thanks in advance!

Était-ce utile?

La solution

I will presume that if you are wanting to cache EF objects, you don't require lazy loading or change tracking on those entities.

I believe that both of those are enabled through object proxies that will cause serialization issues (since you don't want to serialize the proxy).

If you disable the property DbContext.Configuration.ProxyCreationEnabled then serialization of the actual object, not the proxy, should work fine. This is typically required when returning POCO objects over WCF but is likley the same for other serializations scenarios such as this.

Autres conseils

If you detach the EF entity from the DbContext before serializing it, that disables lazy loading, so your custom serializer won't try to serialize anything that isn't already part of the entity's graph.

Then when you get it back from the cache, if you attach it to a new (identical) DbContext, that should reenable lazy loading.

(Caveat: once you detach the entity from the context, any new queries that include that same object will create a new, attached, copy, so you will need to code with some care to avoid running into trouble with multiple potentially-different versions of the same object running around. But that said, this should let you do what you want.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top