3
votes

I have two objects that have a many to many relationship with each other.

I'm using Entity Framework in a Database First approach.

My Database Profiler is showing that everytime I fetch one set of objects A, it loads the other set of object B for each element in A. I assumed that with lazy loading, this wouldn't happen, or that B would be fetched when accessing via the navigation property.

The code to access the objects uses a generic approach, where entities is my DbContext

public virtual IQueryable<T> GetAll()
{
    IQueryable<T> query = entities.Set<T>();
    return query;
}

Both navigation properties are implemented as virtual ICollection<T> and I have Configuration.LazyLoadingEnabled = true explicitly set in my DbContext constructor.

Am I missing something, or approaching this the wrong way? Should I just remove the navigation properties and explicitly load what I need via other queries?

1
Are you watching the loaded A elements in the debugger? Remember that you trigger lazy loading with the debugger when you watch the A elements with their B collections.Slauma
I set LazyLoadingEnabled to false and then the B collections aren't loaded, so I'm not sure why that isAndrew Burgess
It simply means that something in your code touches those navigation properties and executes lazy loading - as @Slauma mentioned even debugging tools are doing this.Ladislav Mrnka
Does calling ToList() on the IQueryable cause the lazy loading to be executed? Without using the debugger, and just using the SQL Server Profiler, I can see that each A object is having the B objects selected, and I don't actually use the navigation property anywhereAndrew Burgess
But this sounds more like eager loading. Are you using Include in your query?Slauma

1 Answers

0
votes

In the presence of the experts I am reluctant to ask this :) but would setting ProxyCreationEnabled=false on the DbContext not help in this case? Sorry if this is too "newbish" of a point