Search code examples
entity-frameworkcachingazureappfabricentity-framework-4.3

Caching Entity Framework results in Azure AppFabric


I'm trying to figure out how to cache EF query results in an Azure AppFabric cache. Currently I'm using the LoreSoft EntityFramework extensions to deal with the caching (http://bit.ly/LWSywm). It works perfectly with an in memory cache, but not so much with AppFabric across multiple VM's. The issue is that I've got virtual properties in my EF objects, and they're being serialized as Dynamic Proxy objects, which of course can't be deserialized on a different VM, or even after a single VM restarts the application.

I only have a few queries I need to cache, so I'd rather not load every single related object manually across the whole project. Is there any way I can serialize an EF object with virtual properties? I don't need the virtual properties to magically start lazy loading again after I deserialize them. I've tried turning off lazy loading the DbContext before serializing the results, but that doesn't work. The only way I've found to get a serializable EF object is the remove all virtual properties.

By the way I've looked at the Julie Lerman article here: http://bit.ly/LWToZT

Seems like a cool project, but I'm not entirely sure it's going to solve my problem of not being able to serialize EF objects. Don't want to go down that road if I'm just going to end up where I started.

Any ideas most appreciated!


Solution

  • You can configure your dbcontext (or object context) to not use proxy objects. Obviously, this means no change tracking and no lazy loading. If you don't eager load an object's navigation properties, they will simply be null instead of references to proxies. It's worth noting that you can toggle this on and off throughout the context's lifetime, so it's not an all or nothing decision.

    If you are using DbContext, the syntax is:

    context.Configuration.ProxyCreationEnabled = false;