我正在为这个论坛进行编码,由于我是LINQ的新手,因此用户访问主页时遇到了这个问题。我想要一个显示这样的论坛列表的表:
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)
谢谢…
如果您使用成员身份并且不想将aspnet_Users包含在dbml中,则用于显示用户名:
... LastPostUserId = posts.OrderByDescending(p=>p.PostId).Take(1).Select(p=> Membership.GetUser(p.UserId)) ...
使发布的示例更好一点的另一项更改是在posts变量中添加orderbydescending:然后,您可以从select子句中删除重复4次的OrderByDescending:
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 }
如果没有最新帖子,请测试此代码,我认为如果Take(1)为null,则可能会引发错误。