2010-05-31 54 views
2

我是LINQ的新手,所以我很擔心一些查詢,我相信這很簡單。無論如何,我一直在嘲笑我的頭,但我很難過。幫助將T-SQL查詢轉換爲LINQ查詢

任何人都可以幫助我將這個T-SQL查詢轉換成LINQ查詢嗎?有一次,我看到它是怎麼做的,我相信我可以重新考慮語法一些問題:

SELECT BlogTitle 
FROM Blogs b 
JOIN BlogComments bc ON 
    b.BlogID = bc.BlogID 
WHERE b.Deleted = 0 
    AND b.Draft = 0 
    AND b.[Default] = 0 
    AND bc.Deleted = 0 
GROUP BY BlogTitle 
ORDER BY MAX([bc].[Timestamp]) DESC 

只是爲了證明我試圖解決這個我自己,這裏是我」已經拿出到目前爲止,雖然它不編譯,更不用說工作...

var iqueryable = 
    from blog in db.Blogs 
    join blogComment in db.BlogComments on 
     blog.BlogID equals blogComment.BlogID 
    where blog.Deleted == false 
     && blog.Draft == false 
     && blog.Default == false 
     && blogComment.Deleted == false 
    group blogComment by blog.BlogID into blogGroup 
    orderby blogGroup.Max(blogComment => blogComment.Timestamp) 
    select blogGroup; 

回答

1
from b in db.Blogs 
where !b.Deleted 
    && !b.Draft 
    && !b.Default 
    && !b.Deleted 
order by b.BlogComments.Max(bc => bc.Timestamp) descending 
select new {Blog = b, Count = b.BlogComments.Count()} 

如果你想返回一個IQueryable<T>,你必須投射到一類,如您RecentlyCommentedBlog。匿名類(我的查詢顯示的內容)不適用於從方法命名爲返回類型。

如果您的Blog類沒有BlogComments屬性create an association

+0

謝謝大衛。正如你所建議的,我選擇通過向Blog部分類添加一個BlogComments屬性來解決這個問題。 – campbelt 2010-06-02 00:09:14

1

我覺得我的工作了,萬一這將是爲別人有用......

var iQueryable = 
from blog in db.Blogs 
join blogComment in db.BlogComments on 
    blog.BlogID equals blogComment.BlogID 
where blog.Deleted == false 
    && blog.Draft == false 
    && blog.Default == false 
    && blogComment.Deleted == false 
group blogComment by blog.BlogTitle into blogGroup 
let maxTimeStamp = blogGroup.Max(blogComment => blogComment.Timestamp) 
let commentCount = blogGroup.Count() 
orderby maxTimeStamp descending 
select new RecentlyCommentedBlog() { BlogTitle = blogGroup.Key, CommentCount = commentCount }; 

我試試以返回此查詢的結果作爲IQueryable對象。如果不創建一個新類,只是爲了這個查詢,我稱之爲RecentCommentedBlog,我無法解決這個問題。以下是一個類的代碼:

public class RecentlyCommentedBlog 
{ 
    public string BlogTitle { get; set; } 
    public int CommentCount { get; set; } 

    public RecentlyCommentedBlog() { } 

    public RecentlyCommentedBlog(string blogTitle, int commentCount) 
    { 
     BlogTitle = blogTitle; 
     CommentCount = commentCount; 
    } 
} 

不管怎麼說,這種解決方案似乎是工作,我不禁覺得肯定是已經完成了這個更好的方法。