2009-10-30 40 views
0

我剛剛開始使用LINQ到SQL。我希望有人可以驗證linq-2-sql延遲執行,直到執行foreach循環。總而言之,有人能告訴我這個代碼是否可擴展。這是一個帶有幾個搜索參數的簡單獲取方法。謝謝!Linq-2-Sql代碼:這是否規模?

代碼:

public static IList<Content> GetContent(int contentTypeID, int feedID, DateTime? date, string text) 
     { 
      List<Content> contentList = new List<Content>(); 
      using (DataContext db = new DataContext()) 
      { 
       var contentTypes = db.ytv_ContentTypes.Where(p => contentTypeID == -1 || p.ContentTypeID == contentTypeID); 
       var feeds = db.ytv_Feeds.Where(p => p.FeedID == -1 || p.FeedID == feedID); 

       var targetFeeds = from f in feeds 
            join c in contentTypes on f.ContentTypeID equals c.ContentTypeID 
            select new { FeedID = f.FeedID, ContentType = f.ContentTypeID }; 

       var content = from t in targetFeeds 
           join c in db.ytv_Contents on t.FeedID equals c.FeedID 
           select new { Content = c, ContentTypeID = t.ContentType }; 

       if (String.IsNullOrEmpty(text)) 
       { 
        content = content.Where(p => p.Content.Name.Contains(text) || p.Content.Description.Contains(text)); 
       } 

       if (date != null) 
       { 
        DateTime dateTemp = Convert.ToDateTime(date); 
        content = content.Where(p => p.Content.StartDate <= dateTemp && p.Content.EndDate >= dateTemp); 
       } 

       //Execution has been defered to this point, correct? 
       foreach (var c in content) 
       { 
        Content item = new Content() 
        { 
         ContentID = c.Content.ContentID, 
         Name = c.Content.Name, 
         Description = c.Content.Description, 
         StartDate = c.Content.StartDate, 
         EndDate = c.Content.EndDate, 
         ContentTypeID = c.ContentTypeID, 
         FeedID = c.Content.FeedID, 
         PreviewHtml = c.Content.PreviewHTML, 
         SerializedCustomXMLProperties = c.Content.CustomProperties 
        }; 
        contentList.Add(item); 
       } 
      } 
      //TODO 
      return contentList; 
     } 

回答

0

取決於你的意思 '尺度' 是什麼。數據庫方這個代碼有可能會造成麻煩,如果你正在處理大型表; SQL Server的優化器在處理where子句謂詞中的「或」運算符時效果很差,並且如果它們中有多個,它們傾向於回退到表掃描。我會去找幾個.Union調用來避免SQL因爲||而回退到表掃描的可能性。

如果您可以共享有關基礎表格和其中的數據的更多詳細信息,將更容易給出更詳細的答案...