2009-08-23 23 views
3

我不是超級熟悉的LINQ to SQL還,但東西給我的印象是這樣的:linq to sql將這個查詢翻譯成如下格式效率不高:「select *」?

var articles = 
    (from a in DB.Articles 
    where 
    a.ArticleId == ArticleId.Question && 
    a.DeletedAt == null && 
    a.Votes >= minVotes 
    orderby a.UpdatedAt descending 
    select a). 
    Take(maxarticles); 

被轉換到這一點:

string query = 
    "select top 10 * from articles 
    where 
    ArticleId = 1 and 
    DeletedAt is null and 
    Votes >= -5 
    order by UpdatedAt desc"; 

這令我出效率低下,LINQ to SQL的願意使用「select *」類型的查詢抽空所有內容。 這不是沒有效率嗎?

爲什麼linq to sql這樣做?

回答

4

如果您要選擇較少的列,你必須在你的LINQ查詢使用投影to SQL來把所有列。

var articles = (from a in DB.Articles 
    where a.ArticleId == ArticleId.Question 
     && a.DeletedAt == null 
     && a.Votes >= minVotes 
    orderby a.UpdatedAt descending 
    select new 
    { 
     a.ArticleId, 
     a.Votes 
    }) 
    .Take(maxarticles); 

做類似上面會轉化爲SQL,看起來像這樣...

select top 10 
     ArticleId, 
     Votes 
from  articles 
where ArticleId = 1 
     and DeletedAt is null 
     and Votes >= -5 
order by UpdatedAt desc 
4

不使用「SELECT *」的理念是避免帶來不必要的列。

在你的情況,你特別問LINQ時指定「選擇」