1

我有两个表:comments 和commentLikes 在同一个查询中我计算用户对评论的喜欢。

我得到了以下(简化的)查询:

var res = (from c in db.Comments
                           where c.Topic.ID == topicID
                           select new
                           {
                               comment = c,
                               count = c.CommentLikes.Count()
                           }).ToList();

但是,我不想再次将likecount 映射到评论实体中,而是希望获得一个评论列表,其中仅包含一个LikeCount 字段,最好使用有效的查询。像这样的东西:

   var res = (from c in db.Comments
                               where c.Topic.ID == topicID
                               select new
                               {
                                   comment = c,
                                   c.LikeCount = c.CommentLikes.Count()
                               }).ToList();

此查询无法编译。

如何在linq中做到这一点?

4

1 回答 1

2

你不能那样做。EF 不支持将 (= select) 数据投影到实体中。LikeCount执行查询后,您必须将属性填充到内存中。您可以以紧凑的方式编写它,但它基本上只是foreach物化匿名对象的循环:

IEnumerable<Comment> res =
          (from c in db.Comments
           where c.Topic.ID == topicID
           select new
           {
               comment = c,
               count = c.CommentLikes.Count()
           })
           .ToList() // DB query runs here, the rest in memory
           .Select(a => {
               a.comment.LikeCount = a.count;
               return a.comment;
           });
于 2012-06-17T00:06:02.817 回答