2014-11-22 83 views
1

我有3個表 - 發佈,評論,贊
評論已連接到帖子由TypeId和PostType,喜歡連接到帖子和評論TypeId和類型,喜歡有一列LikeType,其中0表示喜歡,1分表示不喜歡

現在我想張貼有列表和兩者都應該包含各自的頂和踩LINQ查詢與組連接和計數需要重構

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

我得到的結果,但生成的查詢好像是大的,所以我如何優化。

回答

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