Reputation: 677
I'm looking for the most elegant/best way to load navigation properties after creating an entry.
The situation is this: *I create a row in my table and link 2 other tables by ID. The object I get back only contains the id's, not the actual linked objects. *Through eager loading I want to load those objects
context.Entry(b)
.Reference(e => e.Table1)
.Reference(e => e.Table2)
.Load();
Doesn't seem to work, I can't chain References, so I could either query the complete object:
context
.Objects
.Where(o => o.ID == id)
.Include(o => o.Table1)
.Include(o => Table2)
.FirstOrDefault();
or do this :
context.Entry(b)
.Reference(e => e.Table1)
.Load();
context.Entry(b)
.Reference(e => e.Table2)
.Load();
But this creates (I suspect) 2 calls to the database instead of 1 combined call. Or am I missing another way to chain those references?
Upvotes: 1
Views: 1492
Reputation: 205539
For this specific scenario you can use simple anonymous type projection and rely on the navigation property fix-up as described in Loading Related Data:
Tip
Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.
So the following would do the job:
context.Objects
.Where(o => o.ID == id)
.Select(o => new { o.Table1, o.Table2 })
.Load();
and in theory should be better (should load only the related data). However, due to a current (v1.1.0) EF Core bug it would also include all the root object fields, thus making it equivalent of the variant with Include
s:
context.Objects
.Where(o => o.ID == id)
.Include(o => o.Table1)
.Include(o => o.Table2)
.Load();
I personally would use the first method because the bugs hopefully will be fixed in some future EF Core release, while the second method behavior is "by design".
Upvotes: 2