简体   繁体   中英

LINQ query with group joins and count needs refactoring

I have 3 tables - Post, Comment, Likes
Comment is connected to Post by TypeId and PostType, Likes is connected to Post and Comment by TypeId and Type, Like has a column LikeType, where 0 means Like and 1 means Dislike

Now i want Post with List and both should contain their respective Likes and Dislikes

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();

I get the result, but the query generated seems to be large, so how can i optimize.

Help methods:

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

Help variables:

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

Target query:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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