Linq to sql - 加入2个表,从右表中选择1行,具有1对多的关系

时间:2013-04-16 15:18:33

标签: sql linq linq-to-sql

我正在尝试选择论坛类别和每个相应类别中的最后一篇文章。我已经能够使用OUTER APPLY在SQL中完成此操作,但无法将其成功转换为LINQ。

在SQL中生成所需的结果:

SELECT  fc.CategoryID, fc.CategoryName, fc.PostCount, ft.Title, ft.LastPost, ft.LastPostId, ft.TopicId
FROM    ForumCategory AS fc
OUTER APPLY
    (
    SELECT TOP (1) *
    FROM ForumTopic
    WHERE ForumTopic.CategoryID = fc.CategoryID
    ORDER BY ForumTopic.lastpost DESC
    ) ft

我尝试转换为LINQ:

Dim query = From fc In ctx.ForumCategories _
            Join ft In ctx.ForumTopics On fc.CategoryID Equals ft.CategoryID _
            Select New With {
                                fc.CategoryID, 
                                fc.CategoryName, 
                                fc.PostCount, 
                                ft.Title, 
                                ft.LastPostId, 
                                ft.LastPost.OrderByDescending().First()
                            }

我收到一条错误消息:'OrderByDescending'不是'Date?'的成员。

1 个答案:

答案 0 :(得分:3)

你写如下:

var q = from fc in ctx.ForumCategories
        from ft in (from x in ctx.ForumTopic
                    where x.CategoryID == fc.CategoryID
                    order by x.lastpost desc
                    select new
                    {
                       x.Title, 
                       x.LastPost, 
                       x.LastPostId, 
                       x.TopicId
                    }).Take(1).DefaultIfEmpty()
        select new
        {
           fc.CategoryID, 
           fc.CategoryName, 
           fc.PostCount, 
           ft.Title, 
           ft.LastPost, 
           ft.LastPostId, 
           ft.TopicId
        };