2013-04-25 35 views
1

使用StackExchange.Profiling.MiniProfiler類來對Linq-To-Sql作爲ORM的ASP.NET MVC應用程序進行概要分析。如何改進Linq-To-Sql代碼

我試圖減少一個動作到一個SQL,以便我沒有任何重複了。 因此,我相應地更改了我的linq-to-sql代碼,但它對速度沒有任何正面影響。

然後我檢查了SQL所需的時間。

這顯示了MiniProfiler:

enter image description here

當我火了Management Studio中完全相同的SQL它是超級快:

enter image description here

下面是代碼:

from t in type 
let tDoc = (from d in context.documents 
      where d.Key == t.No 
      && d.RType == (int)RType.Art 
      && d.AType == (int)AType.Doc 
      select d).FirstOrDefault(d => d.UseForThumb) 
select new Time 
{ 
    Id = t.Id, 
    //... more simple mappings here 
    // then a complex one: 
    DocsCount = context.documents.Count(d => 
     (d.Key == t.Id.ToString() 
     && d.RType == (int)RType.Type 
     && d.AType == (int)AType.Doc) 
     || 
     (d.Key == t.No 
     && d.RType == (int)RType.Art 
     && d.AType == (int)AType.Doc)), 

    // and another one 
    ThumbId = (tDoc != null && tDoc.FRKey.HasValue) ? tDoc.FRKey.Value : 0 
}; 

Wha t可以成爲巨大差異的原因嗎? - 編輯:沒有區別,我只是misenterpreted SSMS :(

不管怎麼說,我的問題persits我可以改變什麼,使其更快

我讀一段,從LINQ的 - 到 - 映射? SQL有一個性能問題是有沒有辦法解決這個

+0

您的表現相同:代碼和SSMS中的1sec,不是嗎? – 2013-04-25 13:27:49

+0

哦,是嗎?我雖然在SSMS是1毫秒!尷尬!獲取這12行的速度仍然很慢...... – 2013-04-25 13:41:32

+0

使用fdottrace來判斷髮生了什麼事,不要再猜測了! – 2013-04-25 14:36:44

回答

0

我做了一些試驗和錯誤,改變了LINQ到SQL代碼如下:?

from t in types 
let docs = context.documents.Where(d => (d.RKey == t.Id.ToString() 
            && d.RType == (int)RType.Type 
            && d.AType == (int)AType.Doc) 
            || 
             (d.RKey == t.No 
            && d.RType == (int)RType.Art 
            && d.AType == (int)AType.Doc)) 
let tDoc = docs.FirstOrDefault(d => d.RType == (int)RType.Art && d.UseForThumb) 
let docsCount = docs.Count() 
select new Time 
{            
    Id = t.Id, 
    //... more simple mappings here 
    DocsCount = docsCount, 
    ThumbId = (tDoc != null && tDoc.FRKey.HasValue) ? tDoc.FRKey.Value : 0, 
} 

這多少進行的查詢,多更快。