[英]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.