我有性能问题,不理解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()?
第二个问题如何使它正确?