LINQ查询的一个论坛 [英] LINQ query for a forum

查看:96
本文介绍了LINQ查询的一个论坛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码这个论坛,因为我是新来的LINQ我遇到了这个问题,当用户点击主页。我想显示的论坛列表如下表:

I'm coding this forum and since I'm new to LINQ I ran into this problem when the user hits the main page. I want a table displaying a list of forums like this:

Forum  --- Topics (count) --- Posts (count) --- LastPostUserId --- LastPostTime

我有以下SQL表:

Forums:
ForumId (int32),
Title (string),
Description (string)

ForumThreads:
ThreadId (int32),
ForumId (int32),
UserId (guid),
Subject (string),
Views (int32),
CreateDate (DateTime)

ForumPosts:
PostId (int32),
ThreadId (int32),
UserId (guid),
Post (string),
CreateDate (datetime)

感谢您...

推荐答案

有关,如果您使用的会员,你不希望在您的dbml的aspnet_Users显示用户名:

For displaying the user's name if you use membership and you don't want to include the aspnet_Users in your dbml:

...
LastPostUserId = posts.OrderByDescending(p=>p.PostId).Take(1).Select(p=> Membership.GetUser(p.UserId))
...

另一个变化让你的贴样好一点是添加orderbydescending在帖变量:
然后,你可以放下4次从SELECT子句反复orderByDescending:

Another change to make your posted sample a bit better is to add the orderbydescending in the posts variable: Then you can drop the 4 times repeated OrderByDescending from the select clause:

from forum in Forums
let posts = ForumPosts.Where(p => p.ForumThreads.ForumId.Equals(forum.ForumId)).OrderByDescending(p=>p.PostId)
select new
{
    Forum = forum.Title,
    Description = forum.Description,
    Topics = forum.ForumThreads.Count(),
    Posts = posts.Count(),
    LastPostId = posts.Take(1).Select(p=>p.PostId),
    LastPostThreadId = posts.Take(1).Select(p=>p.ThreadId),
    LastPostUserId = posts.Take(1).Select(p=>p.UserId),
    LastPostTime = posts.Take(1).Select(p=>p.CreateDate)
}

甚至更清洁的:

from forum in Forums
let posts = ForumPosts.Where(p => p.ForumThreads.ForumId.Equals(forum.ForumId))
let lastPost = posts.OrderByDescending(p=>p.PostId).Take(1)
select new
{
    Forum = forum.Title,
    Description = forum.Description,
    Topics = forum.ForumThreads.Count(),
    Posts = posts.Count(),
    LastPostId = lastPost.PostId,
    LastPostThreadId = lastPost.ThreadId,
    LastPostUserId = lastPost.UserId,
    LastPostUserName = Membership.GetUser(lastPost.UserId),
    LastPostTime = lastPost.CreateDate
}

测试此代码时,有没有最新帖子寿,我想这可能抛出一个错误,如果采取(1)为null。

Test this code when there are no last posts tho, I think it might throw an error if Take(1) is null..

这篇关于LINQ查询的一个论坛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆