Entity Framework Fetch count of child entities as a property

c# entity-framework entity-framework-6 sql

Question

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.

1
0
11/21/2016 5:59:49 PM

Popular Answer

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();
1
1/22/2018 11:23:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow