I have 2 entities which depict Post
, and Comments
.
public class Post
{
public int Id { get; set; }
public ICollection<Comment> Comments { get; set; }
//other properties
//Unmapped property
public int NumberOfComments { get; set; }
}
public class Comment
{
public int Id { get; set; }
public Post Post { get; set; }
public int PostId { get; set; }
// other properties
}
Now I want the NumberOfComments
property to be populated with the actual count of comments of the post.
Tried projecting the results of the query in to a collection of posts model didn't workout.
Tried joining the table and then grouped by post id still didn't seems to work.
I cannot simply return p.Comments.Count;
as the property definition as I'm not including the comments during the query. I only wants the count of the comments, not the whole collection in memory.
This is the way I have found to do it.
The following classes would be necessary:
public class PostExtraData
{
public Post post { get; set; }
public int NumberOfComments { get; set; }
}
public class Post
{
public int Id { get; set; }
public ICollection<Comment> Comments { get; set; }
//other properties
}
public class Comment
{
public int Id { get; set; }
public Post Post { get; set; }
public int PostId { get; set; }
// other properties
}
Do not add the PostExtraData
class to the context.
And in the controller we wrote the following (in this case, to obtain the list of posts):
return _context.Post
.Select(p => new PostExtraData
{
Post= p,
NumberOfComments = p.Comments.Count(),
})
.ToList();