8

In EF 4, can I do eager loading of navigation properties by writing sql on DbContext.Database.SqlQuery or DbContext.Set<T>().SqlQuery? I don't seem to be getting my navigation properties populated.

Edit

It seems I can do eagerloading with DbContext.Set().SqlQuery, just not DbContext.Database.SqlQuery. Any idea why?

enamrik
  • 2,292
  • 2
  • 27
  • 42
  • DbContext.Set().SqlQuery does not do eager loading; it does lazy loading. You can see this if you output the sql executed and step through the code, using : db.Database.Log = message => { Debug.WriteLine(message); }; – an phu Oct 13 '15 at 20:35

1 Answers1

4

DbSet.SqlQuery works differently than Database.SqlQuery. The method on DbSet applies to the given entity set. It has to return entities of the given type and by default the returned entities will be tracked. Database.SqlQuery can return any object (possibly not an entity) and the returned objects are never tracked by the context. You may also want to take a look at msdn to compare both methods:

Database.SqlQuery - http://msdn.microsoft.com/en-us/library/gg679117(v=vs.103).aspx

DbSet.SqlQuery - http://msdn.microsoft.com/en-us/library/system.data.entity.dbset.sqlquery(v=VS.103).aspx

Pawel
  • 31,342
  • 4
  • 73
  • 104
  • Thanks for responding. I already know about the tracking part. I'm wondering why my navigation properties won't get populated. When I do joins on tables with 1-M relationships (raw sql) I expect my navigation properties to be eagerloaded. It does with DbContext.Set().SqlQuery but for some reason, it doesn't with DbContext.Database.SqlQuery. – enamrik Feb 04 '12 at 12:07
  • Can you show the code where it populuates navigation properties? Both methods eventually call ObjectContext.ExecuteStoreQuery and I don't think it populates navigation properties (at least it did not when I tried). – Pawel Feb 04 '12 at 20:46
  • the gist example does lazy loading of the author navigation property, not eager loading as requested in the question. – an phu Oct 13 '15 at 19:57