aventic
aventic

Reputation: 1524

Number of comments in post

I'm trying to count number of comments from within a post (trying to create some sort of blog) and displaying it in the post's title. Here is some code.

My models:

public class Post
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public string Author { get; set; }
    public DateTime DateTime { get; set; }

    public List<Comment> Comments { get; set; }
}

public class Comment
{
    public int ID { get; set; }
    public int PostID { get; set; }
    public string Message { get; set; }
    public string Author { get; set; }
    public DateTime DateTime { get; set; }
}

My controller:

public ActionResult Index()
{
    var dbPosts = (from p in db.Posts
                orderby p.ID descending
                select p).ToList();

    return View(dbPosts);
}

My view:

@foreach (var post in Model) {
    **@post.Comments.Where(x => x.PostID == post.ID).Count()**

    <h3>@Html.ActionLink(post.Title, "Details", new { id = post.ID })</h3>
    <span class="written">skrevet d. @post.DateTime.ToLongDateString() @post.DateTime.ToShortTimeString() af @post.Author</span>
    <p>@post.Message</p>
    <hr />
}

I have marked my error with stars. It gives me an error saying "Value cannot be null."

Anyone who can help me figuring this out?

Kind regards and thanks in advance

Upvotes: 0

Views: 334

Answers (1)

Lars
Lars

Reputation: 1948

In your View in foreach loop you are accessing your post, so just do

@post.Comments.Count

Also I think your query in Controller might lazy load Comments and they aren't actually included when you send them to your View, so eager load Comments:

var dbPosts = db.Posts.Include("Comments").OrderByDescending(p => p.ID).ToList(); 

Upvotes: 3

Related Questions