8

Is there a way to get entity objects to automatically pull all relevant data through the relationships instead of having having to .Include everything I want populated? I can't use lazy loading as this needs to be serialized to go over WCF. It would just be fantastic to have it auto populate the relevant collections.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
Dylan
  • 1,919
  • 3
  • 27
  • 51

2 Answers2

10

No there is no build in feature which will automatically eagear load whole object graph. You must always explicitly say which navigation properties you want to eager load (by using Include method or LoadProperty method).

Edit:

Based on your comment: Generally it should be possible to build some auto loader - but it will not be easy. ObjectContext has MetadataWorkspace property which contains all metadata about your entities. You can load all information about your entities from metadata and add needed inclueds to the query. I expect one problem - you must somehow handle cyclic references. If you need some example how to extract information about entities check T4 POCO generation template.

Dabblernl
  • 15,831
  • 18
  • 96
  • 148
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Ok. Then is there a more generic way to go through all the relationships and load the data? – Dylan Feb 15 '11 at 08:47
  • @Dylan: I added some idea into my answer. – Ladislav Mrnka Feb 15 '11 at 09:19
  • Is there not someway to modify the generated T4 code to pull through the required content in the collections? – Dylan Feb 15 '11 at 10:31
  • @Dylan: You can modify T4 to create such collections for you. – Ladislav Mrnka Feb 15 '11 at 10:34
  • 3
    Has the situation changed with EF 6.1 ? – Alex Bitek Jan 11 '14 at 16:36
  • That's too bad if that's the case. While normal usage scenarios may not require this, it would be convenient in certain subcutaneous testing scenarios where you want to express as simply as possible that retrieving entity X from the database has property Y without the overhead of maintaining an open DbContext (i.e. MyAppDatabase.Get().SomeCollection.ShouldNotBeNull();) – Derek Greer Jul 17 '15 at 14:07
  • Also see http://stackoverflow.com/questions/43754005/entityframework-eager-loading-with-excludes-instead-of-includes – Stefan May 03 '17 at 14:16
0

I came across this querstion recently because I was looking for something similar.

Since EF Core 6 there is a AutoInclude method that configures whether a navigation should be included automatically.

This can be done in the OnModelCreation method in the DbContext class:

modelBuilder.Entity<Theme>().Navigation(e => e.ColorScheme).AutoInclude();

This would load the ColorScheme for every Theme when running the query:

var themes = context.Themes.ToList();

See Model configuration for auto-including navigations

Ado
  • 637
  • 1
  • 6
  • 17