15

Please how can I disable dynamic proxies for all entities created in Entity Framework 5.

Currently, I am setting this espEntities.Configuration.ProxyCreationEnabled = false; in every instance of a DbContext is there a way I can do this for current and future models as a one time task.

Thanks

0

1 Answer 1

27

Method 1

If you have an EDMX model, a partial class is created. Use that and in the OnContextCreated you can disable ProxyCreationEnabled

public partial class MyModelContainer
{
    public void OnContextCreated()
    {
        this.Configuration.ContextOptions.ProxyCreationEnabled = false;
    }
}

Method 2

Edit the model.tt file. Find the line containing something like this:

partial class <#=code.Escape(container)#> : DbContext

And add in

this.Configuration.ProxyCreationEnabled = false;

Method 3

If you are not using an EDMX file, do it in your context constructor: (assuming your context is called EspEntities)

public class EspEntities : DbContext
{
   public EspEntities()
   {
      Configuration.ProxyCreationEnabled = false;
   }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Hello David,I assume the context constructor in this case is found in the model.context.cs. However, if this is the case, it creates an issue if the EDMX model is updated and the changes will be overwritten?
Proxy creation != lazy loading. Lazy loading does require proxy creation, but disabling it doesn't disable proxy creation. Proxy creation is also required (and used) for e.g. change tracking. Your original option is good, as long as you either make the change in the template (instead of the template's output), or add it to a new file (the class should be a partial class, so it can be extended in other files).
Thanks once again David for the quick response...however, this just disables lazyloading and the dynamic proxies are still generated...?
@hvd you mean I should extend the model.context.cs by creating a new partial class and override the existing constructor? in between any good tip on making this change in the model.tt file?
Ah yes sorry, another change made.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.