Question

I have a problem with EF5 DbContext when changing the configuration after using it. I am using POCO T4 template. Here is the scenario:

  • I query a set in my context and get dynamic proxy objects with their relations
  • I modify the configuration of the context to disable dynamic proxies and lazy loading like this:

    context.Configuration.ProxyCreationEnabled = false;
    context.Configuration.LazyLoadingEnabled = false;
    
  • I then query again on a set and get the same kind of results with proxies and relations.

What do I need to do to take the configuration into account after the context had been initialized? Is it possible?

Thanks in advance!

Was it helpful?

Solution

If you query a set, disable proxy creation and query the same set again you have a big chance to get proxied entities anyway. The reason is identity map used internally in the context. Each entity can be tracked by the context only once. So if you query the set with proxy creation enabled, EF will create entity instance with dynamic proxy for every unique record loaded from the database. When you query the set again after disabling proxy creation, EF will reuse all already created entities (with their proxies) and create new ones without dynamic proxies only for records which hasn't been loaded yet.

If you want to avoid those proxies you must either:

  • Turn off proxy creation before the first query
  • Use a new context for the second query

You can also try to use AsNoTracking() but I have suspicion that it will not work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top