EF - Getting metadata about related entities by eager loading to avoid
extra DB calls
Scenario:
I have Users. Each user can be an "author" to an Article. (An article can
have several collaborating "authors".)
I want to present a GUI interface to search for an User by name. You will
be presented a list where the authors who have any articles have a link to
their articles, while the ones with zero still will be presented but
without the link.
Implementation:
I present a search interface for the client. They send the search string
to my UserSearchForArticlesList-controller where I ask EF for all the
Users that have a name that match the search query and sent this list to
my View.
The view iterates through the list of Users. For each it checks if it has
any documents that is public (Connection table for User<->Article, I know
that EF can solve this without making this visible, but that's how it is
now.) If the User has connections to public Articles, it creates an
ActionLink, counts the public articles and presents this count by the
link.
Controller (without eager loading):
[HttpGet]
public ActionResult UserSearchForArticlesList(string searchTerm)
{
var model = myEF.Users.Where(x =>
x.Name.Contains(searchTerm)).OrderBy(x => x.Name)};
return View("Index", model);
}
View:
@foreach (var item in Model)
{
if (item.UserArticles.Any(o => o.Article.IsPublic))
{
<li>@Html.RouteLink(item.Name, "UserArticles", new { item.Id
}) (@item.UserArticles.Count(o => o.Article.IsPublic))</li>
}else
{
<li title="No public articles for this User">@item.Name</li>
}
}
Problem:
With lazy loading the relations for the User, I get approx 7 DB calls for
EACH User I present in the list. When I eager load (.Inlude(user =>
user.UserArticles.Articles)) I get only one call, but with way to much
data then I actually need.
Is it possible that you somehow can get EF to get the matching Users and
the count of the connected public Articles for that user, using only a
reasonable amount of DB calls?
"Just after writing a big article about my problem"-insight:
It actually just hit me when debugging and looking at the EF profiler that
both the if-clause and the count in the View is resulting in a lot of
single row querys to the DB. Why is this? Shouldn't EF figure out some
minified SQL queries for this?
No comments:
Post a Comment