Question

Firstly, I'd like show you my model.

public class Blog
{
    [Key]
    public int BlogID { get; set; }
    public System.Nullable <DateTime> LastModified { get; set; }
    public System.Nullable<int> AidID { get; set; }
    public virtual BlogAid BlogAid{ get; set; }
    public System.Nullable<int> AuthorID { get; set; }
    public virtual BlogAuthor BlogAuthor { get; set; }
    public System.Nullable<int> CommentID { get; set; }
    public virtual ICollection<BlogComment> BlogComment { get; set; }
    public System.Nullable<int> TitleID { get; set; }
    public virtual BlogTitle BlogTitle { get; set; }
    public System.Nullable<int> ContentID { get; set; }
    public virtual BlogContent BlogContent { get; set; }
    public System.Nullable<int> NewsID { get; set; }
    public virtual BlogNews BlogNews { get; set; }
}

Especially for this line:

public virtual ICollection<BlogComment> BlogComment { get; set; }

That means I have 1-to-many relationship between blog and comments, then see my controller:

var comments = from c in DB.BlogCommenttbl
                      join b in DB.Blogtbl on c.BlogID equals b.BlogID
                      where c.CommentID > 0
                      select new
                      { Comments = c.Comments, LastModified=c.LastModifed};

if (comments.FirstOrDefault() !=null)
{
    bpm.Blogs.BlogComment = new List<BlogComment>();

    foreach (var item in comments.ToList())
    {
        bpm.Blogs.BlogComment.Add(new BlogComment{Comments=item.Comments, LastModifed=item.LastModified});
    }
}

and the view is

@foreach (var item in Model.Blogs.BlogComment)
{
    <h3>Start Bootstrap <small>@Html.DisplayText(item.LastModifed.ToString())</small></h3>
    <p>@Html.DisplayText(item.Comments.ToString())</p>
}

but I got Object reference not set to an instance of an object. error.

Then I debugged the code and found that

bpm.Blogs.BlogComment = new List<BlogComment>();

can not work, so how can I fix this bug? Or handle this issue?

Was it helpful?

Solution

Probably, you didn't initialise bpm.Blogs property. Before line bpm.Blogs.BlogComment = new List<BlogComment>(); you must initialise Blogs:

bpm.Blogs = new Blog();

OTHER TIPS

if (comments.FirstOrDefault() !=null)
{
    bpm.Blogs.BlogComment = new List<BlogComment>();

    foreach (var item in comments.ToList())
    {
        bpm.Blogs.BlogComment.Add(new BlogComment{Comments=item.Comments, LastModifed=item.LastModified});
    }
}

If comments does not contain any items the code block will not get executed. If is not executed, bpm.Blogs.BlogComment will not be instantiated. Change this to:

bpm.Blogs.BlogComment = new List<BlogComment>();

if (comments.FirstOrDefault() !=null)
{
    foreach (var item in comments.ToList())
    {
        bpm.Blogs.BlogComment.Add(new BlogComment{Comments=item.Comments, LastModifed=item.LastModified});
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top