Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically Enabling/Disabling Entity Proxies

I am using the Entity Framework 4.1 with POCO entities in a new project. Everything was working fine until I began caching the entities using AppFabric Caching. I started getting erros retrieving the entitis from the cache related to deserializing the proxy objects. I fixed this problem by setting ContextOptions.ProxyCreationEnabled = false. The issue now is when I get entities back from the cache, I have to attach the entity to the current context using ObjectSet.Attach(entity) and add them to the state manager using ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified).

My question is is there a way to programmatically enable/disable the proxy for a set of entities? Or in other words a way to wrap the deserialized entity in the proxy object.

If there is not a good way to do this, is the way I am doing it now correct? Or is there a better way?

like image 707
Joshua Dale Avatar asked Apr 19 '11 16:04

Joshua Dale


1 Answers

You are using it the correct way. The only way to programatically enable or disable proxy creation is setting ContextOptions.ProxyCreationEnabled to false or true as you do at the moment.

I don't think there is the way to wrap deserialized entity into proxy object. The problem is that the proxy is dynamically created type (= type created at runtime) derived from your entity type. So if you deserialize it to your entity type you can't cast it to other type.

What can probably work is using proxies but disabling LazyLoading (also in ContextOptions) and manually detaching entities from the context which loads them. But it will break all relation and you will still have to attach the entity to the new context and set its state. Another solution which can work is creating new entity by context.CreateObject and copying all data from cached entity to the new one but that is solution which I don't like.

Said in other words: Once you are working with detached entities you must deal with attaching and setting state manually. This is even worse if you are going to change relations.

Btw. you mentioned using EFv4.1 but all the stuff you are using is EFv4. EFv4.1 didn't make any change to ObjectContext API, it added different DbContext API so unless you are casting DbContext back to ObjectContext you are using EFv4. If you cast DbContext back to ObjectContext then you should check DbContext API because it offers equivalents of Attach or ChangeObjectState => DbSet.Attach ande context.Entry(entity).State.

like image 165
Ladislav Mrnka Avatar answered Nov 15 '22 09:11

Ladislav Mrnka