devfunkd
devfunkd

Reputation: 3234

Entity Framework hangs on DynamicProxies loaded

I am trying to diagnose a severe performance issue in my application. It's been almost a week and I am not sure where or what is causing it, except today I noticed the following "Loaded 'EntityFrameworkDynamicProxies' line was holding up things for almost 2 minutes. What is this? Why is it so slow and how can I improve it?

enter image description here

Upvotes: 3

Views: 1424

Answers (2)

MyDaftQuestions
MyDaftQuestions

Reputation: 4691

For me, the issue was due to my poorly used async/await code! As per the OP, it was hanging for the same reason, but I got 0 error messages.

The only way I could resolve it was sticking a break point where the application starts and stepping through. It wasn't super quick, but it wasn't a big task either.

Upvotes: 0

CodeNotFound
CodeNotFound

Reputation: 23200

When creating instances of POCO entity types, the Entity Framework often creates instances of a dynamically generated derived type that acts as a proxy for the entity. This proxy overrides some virtual properties of the entity to insert hooks for performing actions automatically when the property is accessed. For example, this mechanism is used to support lazy loading of relationships.

Source : Data Developer Center

You can disable it by setting this line this.Configuration.ProxyCreationEnabled = false; in your DbContext constructor.

If disabled, you may encounter some problems somewhere in your application when existing code rely on Lazy Loading to load related data. You have to fix those problems by using Explicit Load or Eager Load.

  • Eager Loading by using Include method of your DbSet like db.Persons.Include(p => p.Cars).Include(p => p.Pets).Include(p => p.Children).Where(p => p.Id == personId);
  • Explicit Loading by using the change tracker and Load method on your entry like this : db.entry(person).Collection(p => p.Cars).Load(); for collection navigational property or db.entry(person).Property(p => p.Home).Load(); for simple navigational property.

Lazy Loading, Explicit Loading or Eager Loading, there is no silver bullet for improving your application performance if you are not using EF correctly. There are some things to check in your code to make sure you are:

  • using ToList(), ToArray() etc... to execute your query only once and prevent same request to the database when you need to reiterate on the query.
  • not filtering on client side. I mean make sure you create your query with correct filters before sending query to your database.
  • creating SQL Views for queries if you see that the generated SQLs by EF are not efficient. Copy the generated SQL and analyze the Execution Plan on SSMS.

There are many things that can be improved depending on what your application is doing and need. You can use cache to avoid future request etc...

Upvotes: 1

Related Questions