NDym
NDym

Reputation: 91

Getting count of post comments Entity Framework

I have struggled with this for some time...

I have to implement the counting number for each Blog Comments that has been put over sets of Blog Post.

public class Blog
{

    public int BlogId { get; set; }
    public string BlogPostName { get; set; }
    // ... //
    public virtual ICollection<BlogPostComments> BlogPostComments { get; set; }
}

public class BlogPostComments
{
    public int BlogPostCommentsId { get; set; }
    public string NameOfUser { get; set; }
    public string CommentsOfUser { get; set; }
    public Nullable<System.DateTime> PostedDate { get; set; }
    public Nullable<int> BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

They are in one to many relation - 1 BlogPost can have 0 or more BlogPostComments. For example I have an input from array of integers int[] ids which contains the BlogId 1,2 and 3.I want to fetch all related with those ID comments in dictionary format. At the moment i`m able to get the numbers of comment for all BlogPost with this

public IHttpActionResult Get([FromUri] int[] ids)
{

    var blogPosts = (from blogPost in EntityContext.BlogPostComments
                     where ids.Contains(customer.BlogId.Value)
                     select blogPost);
    int numberOfAllComments = blogPosts.Count();

    return Ok(numberOfAllComments);
}

Let say - first BlogPost have 3 comments, second BlogPost have 5 comments and third BlogPost have 7 comments.

Is there a way to separate the comments for first post and comments for the second post and return them as key value pair with Entity Framework. Please help me to construct or modify my query.

Upvotes: 0

Views: 291

Answers (1)

Andre Andersen
Andre Andersen

Reputation: 1211

You should be able to do something like this:

var postsAndComments = blogRepo
    .Where(blog => ids.Contains(blog.BlogId))
    .Select(p => new { id = p.BlogId, comments = p.BlogPostComments.Count() })
    .ToDictionary(p => p.id, p => p.comments);

Upvotes: 2

Related Questions