2011-02-09 50 views
0

是否有可能在执行asp.net mvc 2操作期间为以下特定情况和一般情况减少往返数据库的次数? 我正在使用linq-to-sql。 下面的代码产生了60个选择,其中60个往返到数据库。我怎样才能减少往返次数?减少往返次数 - linq-to-sql

如果需要更多我的代码,我会发布它。

我的视图模型:

public class ArticlesContainerViewModel 
{ 
    public ArticlesContainerViewModel() 
    { 
    } 

    public Article CategoryArticle { get; set; } 

    public IList<ArticlesNode> CategoryNodes { get; set; } 
} 

public class ArticlesNode 
{ 
    public Article NodeArticle { get; set; } 

    public IQueryable<Article> NodeItems { get; set; } 
} 

的观点:

<ul class="tabs"> 
     <% foreach (var category in Model) 
      { %> 
     <li><a href="#" class="s"> 
      <%= Html.Encode(category.CategoryArticle.AbbreviatedTitle) %></a></li> 
     <% } %> 
    </ul> 
    <!-- tab "panes" --> 
    <div class="panes"> 
     <% foreach (var category in Model) 
      { 
     %> 
     <div> 
      <table style="width: 100%;" cellpadding="0" cellspacing="0"> 
       <% int counter = 0; foreach (var node in category.CategoryNodes) 
        { 
       %> 
       <%if (counter % 2 == 0) 
        { %> 
       <tr> 
        <%} %> 
        <td class="content-container"> 
         <div class="index-node-title"> 
          <%= Html.Encode(node.NodeArticle.ArticleTitle)%>&nbsp;<span class="small1 darkGrey2">(<%= Html.Encode(node.NodeItems.Count().ToString())%>)</span> 
         </div> 
         <div class="index-node-content"> 
          <ul class="index-node-content-list"> 
           <% foreach (var item in node.NodeItems.Take(2)) 

回答

1

的代码是一个有点混乱,如果你问我,我猜的Model类型是IList<ArticlesContainerViewModel>型或相似的东西。你的问题是你在应用程序中使用这个“高”的IQueryable。我会去的结构是:你应该能够因为你现在不必只得到两个查询,而不是m*(n+1)

1. First select all categories and put that in your `ViewModel` using a single query. 
2. From all your categories select all your articles or what else from the db in a single query, put the result in a dictionary where category is the key. 

这样。

+0

谢谢,会试试看,好像是一种更有效率的做事方式... – user560498 2011-02-09 11:46:11