如果您使用成员身份并且不想在您的 dbml 中包含 aspnet_Users,则可以显示用户的名称:
...
LastPostUserId = posts.OrderByDescending(p=>p.PostId).Take(1).Select(p=> Membership.GetUser(p.UserId))
...
让您发布的示例更好的另一个更改是在帖子变量中添加orderbydescending:
然后,您可以从选择子句中删除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)为空,可能会引发错误。