问题
When going through a learning article about related entity loading in Entity Framework MSDN, I came across the following:
It is also possible to eagerly load multiple levels of related entities. The queries below show examples of how to do this for both collection and reference navigation properties.
...[Examples demonstrating the above]...
Note that it is not currently possible to filter which related entities are loaded. Include will always being in all related entities.
This seems slightly confusing, because the two statements seem to be in contradiction to each other. Am I missing something here?
For example, I could specify the Mother
navigation property should be included for every Child
in a Children
DBSet I am querying, like so:
Dim myQuery = From children In context.Children.Include("Mother")
Select child
Does that mean the Father
navigation property will also be eagerly evaluated for every Child
?
If this is not the case (Include
only eagerly loads what you tell it to), is there a way to eagerly load all navigation properties without specifying them?
回答1:
Yes, highlighted this way it is a bit confusing. And your confusion is also caused by the fact that you happen to focus on reference navigation properties.
Looking at collections makes it clear.
it is not currently possible to filter which related entities are loaded
which means: you can only load all entities in a child collection, not entities that meet some condition. Never will other navigation property be loaded than the ones specified in the Include
.
The Include
method started out as the method with the string argument that you show. Later, an extension method was added that allows specifying the navigation properties by expressions:
context.Children.Include(c => c.Mother)
especially when a collection is Include
d:
context.Parents.Include(c => c.Children)
it seems very natural that the collection could be filtered:
context.Parents.Include(c => c.Children.Where(x => x.IsActive))
It compiles, but this is not possible (runtime exception). The reason is that the expression is only used to obtain the name of the nav property in order to call the original Include
method (with the string argument).
I think this is the reason why this restriction is emphasized in the post you refer to.
is there a way to eagerly load all navigation properties without specifying them
No, there isn't. That would be "dangerous", because having many Includes
is a real performance killer. You better specify Includes
carefully.
来源:https://stackoverflow.com/questions/17073557/does-include-load-all-related-entities-or-the-specified-ones