繁体   English   中英

具有组联接和计数的LINQ查询需要重构

[英]LINQ query with group joins and count needs refactoring

我有3张桌子-发表,评论,喜欢
Comment通过TypeId和PostType连接到Post,Likes通过TypeId和Type连接到Post和Comment,Like具有LikeType列,其中0表示Like,1表示Dislike

现在我要发布带有列表的帖子,并且两者都应包含各自的“喜欢”和“不喜欢”

var post = (from c in Db.Comments
                where c.Type == Model.PostType.Post.ToString()
                group c by c.TypeId
                into com
                join p in Db.Posts on com.Key equals p.Pid
                where p.Pid == postId
                select new
                {
                    Post = p,
                    Comments = com.Select(c=>new{Comment=c,like =Db.Likes.Count(
                                    l => l.TypeId==c.CommentId&&l.Type==Model.PostType.Comment.ToString()&&l.LikeType==(int)Model.LikeType.Like)
                    ,dislike =Db.Likes.Count(
                                    l => l.TypeId==c.CommentId&&l.Type==Model.PostType.Comment.ToString()&&l.LikeType==(int)Model.LikeType.Dislike)}),
                    Likes = Db.Likes.Count(l => l.TypeId == p.Pid && l.Type == Model.PostType.Post.ToString() && l.LikeType == (int)Model.LikeType.Like),
                    Dislikes = Db.Likes.Count(l => l.TypeId == p.Pid && l.Type == Model.PostType.Post.ToString() && l.LikeType == (int)Model.LikeType.Dislike),
                }).FirstOrDefault();

我得到了结果,但是生成的查询似乎很大,所以我该如何优化。

帮助方法:

int LikeCount(DbLikes likes, int typeId, int type, int likeType)
{
  return likes.Count(like => 
    like.TypeId == typeId && 
    like.Type == type && 
    like.LikeType == likeType);
}

帮助变量:

var commentType = Model.PostType.Comment.ToString();
var postType = Model.PostType.Post.ToString();
var likeType = (int)Model.LikeType.Like;
var dislikeType = (int)Model.LikeType.Dislike;

目标查询:

var post = (
  from c in Db.Comments
  where c.Type == postType
  group c by c.TypeId into com
  join p in Db.Posts on com.Key equals p.Pid
  where p.Pid == postId
  select new
  {
    Post = p,
    Comments = com.Select(c => new
      {
        Comment = c,
        like = LikeCount(Db.Likes, c.CommentId, commentType, likeType),
        dislike = LikeCount(Db.Likes, c.CommentId, commentType, dislikeType)
      }),
    Likes = LikeCount(Db.Likes, p.Pid, postType, likeType),
    Dislikes = LikeCount(Db.Likes, p.Pid, postType, dislikeType),
  }).FirstOrDefault();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM