[英]LINQ query with group joins and count needs refactoring
I have 3 tables - Post, Comment, Likes 我有3张桌子-发表,评论,喜欢
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 Comment通过TypeId和PostType连接到Post,Likes通过TypeId和Type连接到Post和Comment,Like具有LikeType列,其中0表示Like,1表示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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.