I created a generic repository that handles querying my entities.
When I call this:
public IQueryable<TEntity> GetQuery()
{
return _context.Set<TEntity>().AsQueryable(开发者_StackOverflow社区);
}
I get back the entire entity including all child entities.
When I call this:
public TEntity GetById(Guid id)
{
return GetQuery().Where(e => e.Id == id).FirstOrDefault();
}
I have to specify what child entities to include.
Is there a way to get back ALL child entities without having to write includes for each entity?
Lazy loading is enabled by default. This means that the collections will be loaded when you access them, not when you retrieve the parent object e.g.
foreach (var parent in repo.GetQuery()) {
foreach (var child in parent.Children) {
// do something
}
}
If you wish to eagerly load your entities you could subclass your generic repository and override the methods where you wish to use the Include
lambda. Alternatively there is an Include method that accepts a string list of associations to include, which you could expose on your generic repository.
Update:
Not quite sure why you gave my answer -1 but as further clarification.
You stated regarding your GetQuery() method:
I get back the entire entity including all child entities.
The child entities are lazily loaded, whether you access the collections in debug or output them on your page.
The single query should work, with lazy loading enabled.
And AFAIK, with lazy loading disabled, this doesn't mean that all the collections are loaded automatically, quite the opposite, you have to explicitly load them by calling Include.
精彩评论