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

时间:2014-11-22 10:45:44

标签: c# linq entity-framework

我有3张桌子 - 帖子,评论,赞 注释通过TypeId和PostType连接到Post,Likes通过TypeId和Type连接到Post和Comment,Like有一个LikeType列,其中0表示Like,1表示不喜欢

现在我想要Post with List,两者都应该包含各自的喜欢和不喜欢

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

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

1 个答案:

答案 0 :(得分:0)

帮助方法:

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