帮助将T-SQL查询转换为LINQ查询

时间:2010-05-31 23:20:53

标签: linq tsql group-by max

我是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

只是为了表明我已经试图自己解决这个问题,这是我到目前为止所提出的,虽然它没有编译,更不用说工作了...... / p>

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;

2 个答案:

答案 0 :(得分: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;
    }
}

无论如何,虽然这个解决方案似乎有效,但我不禁认为确实有更好的方法可以实现这一目标。

答案 1 :(得分: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>,则必须投射到诸如RecentCommentedBlog之类的课程中。匿名类(我的查询显示的内容)不适合从方法中命名为返回类型。

如果您的Blog类没有BlogComments属性create an association

相关问题