我有性能問題,不理解EF的行爲。我使用ASP.NET MVC應用程序,並在模型下面的代碼:ASP.NET MVC,實體框架和性能
public List<Portal> PortalListWithCategories()
{
List<Portal> q = new List<Portal>();
q = (from i in _dataContext.Portals.Include("Categories").Include("Ideas") where i.Categories.Count > 0 orderby i.DefaultPortal descending select i).ToList();
return q;
}
我把它從控制器:
portalList = _repository.PortalListWithCategories();
按照我的理解,應該EF執行批處理請求,並與返回門戶網站的集合嵌套集合「類別」和「想法」。
但在視圖我有以下幾點:
@foreach (var category in portal.Categories.Where(n => n.Ideas.Count > 0 && n.Portals.Any(g => g.PortalID == portal.PortalID)))
{
if ((from e in category.Ideas where e.Portals.Any(t => t.PortalID == portal.PortalID) select e).Count() > 0)
{
string categoryLink = Url.RouteUrl("Full", new { PortalID = portal.PortalID, CategoryID = category.CategoryID, action = "Ideas" });
List<NEOGOV_Ideas.Models.Ideas> ideas = category.Ideas.Where(o => o.Portals.Any(p => p.PortalID == portal.PortalID) && o.Categories.Any(h => h.CategoryID == category.CategoryID)).OrderByDescending(k => k.CreatedDateTime).ToList();
<div class="grid_4">
<h4>
<a href="@categoryLink">@category.CategoryName<span class="count_link"> (@ideas.Count())</span>
<span class="follow_link">»</span></a></h4>
<ul>
@foreach (var idea in ideas.Take(3))
{
string ideaLink = Url.RouteUrl("IdeaShort", new { id = idea.IdeaID });
if (!idea.IdeaTypeReference.IsLoaded) { idea.IdeaTypeReference.Load(); }
string cssclass = " class=\"" + idea.IdeaType.TypeName.ToLower() + "\"";
<li><a href="@ideaLink" @cssclass>@idea.Title</a></li>
}
</ul>
</div>
if (i == 2)
{
<div class="clear">
</div>
}
i++;
}
}
按照我的理解,我不應該有新的要求數據庫,但我已經和很多。爲什麼?
[ADDED]
我發現這個字符串 (從E在category.Ideas其中e.Portals.Any(T => t.PortalID == portal.PortalID)選擇e).Count之間() 產生許多請求到DB等:
EXEC sp_executesql的N'SELECT [Extent2] [PortalID] AS [PortalID], [Extent2] [PortalName] AS [PortalName], [Extent2]。 [DefaultPortal] AS [DefaultPortal] FROM [dbo]。[PortalIdeas] AS [Extent1] INNER JOIN [dbo]。[Portals] AS [Extent2] ON [Extent1]。[PortalID] = [Extent2]。[PortalID] WHERE [Extent1]。[IdeaID] = @ EntityKeyValue1',N'@ EntityKeyValue1 int' ,@ EntityKeyValue1 = 5618
爲什麼它發生Count()?
第二個問題如何使它正確?