Elger Mensonides
Elger Mensonides

Reputation: 7029

Linq query select count into same entity

I got two tables: comments and commentLikes in the same query i count the likes users have given on a comment.

I got the following (simplified) query:

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

But, rather than mapping the likecount into the comment entity again, I'd like to get a list of Comments only with a field LikeCount in it, preferably with an efficient query. Something like this:

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

This query doesn't compile.

How to do this in linq?

Upvotes: 1

Views: 978

Answers (1)

Slauma
Slauma

Reputation: 177133

You can't do that. EF does not support to project (= select) data into an entity. You must fill the LikeCount property in memory after the query has been executed. You can write it in a compact way, but it's basically just a foreach loop over the materialized anonymous objects:

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

Upvotes: 2

Related Questions