Eager loading Entity framework core

c# entity-framework-core

Question

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?

1
1
11/27/2018 10:27:41 AM

Accepted Answer

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 Includes:

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".

2
11/27/2018 10:24:17 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow