2011-02-09 48 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